Java Se反射实现类跟方法的注解扫描

Java Se实现类跟方法的注解扫描

也就是后面spring自动扫描的原理

直接上代码了
	1、定义一个用来标识的类的注解
package test.qifanedu.reflection;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;



@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Component {
     

}
2、定义一个用来标识方法的注解
package test.qifanedu.reflection;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Auth {
     
}

3、开始写业务代码
package test.qifanedu.reflection;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;


public class PackageScan {
     

    public static void main(String[] args) {
     
        Class calzz = PackageScan.class;
        Package pkg = calzz.getPackage();//获取包名
        String rootPkg = pkg.getName().split("\\.")[0];//获取包名的开头
        URL resource = calzz.getResource("/"+rootPkg);//获取包的路径
        if (resource.getProtocol().startsWith("file")){
     //判断是file协议开头
           String path =resource.getFile().substring(1);//去除开头的/
           File file = new File(path);
           mkdir(file,rootPkg);
        }
    }
    public static void mkdir(File file,String rootPkg){
     
        File[] files = file.listFiles();
        //获取包里面所有的文件
        for (File f:files){
     
            if (f.isDirectory()){
     
                //如果是文件夹就继续调用自己
                mkdir(f,rootPkg+"."+f.getName());
            }
            if (f.isFile()){
     
                //判断是否为.class的文件
                if (f.getName().endsWith(".class")){
     
                    //去掉后缀
                    String clazzName =f.getName().substring(0,f.getName().lastIndexOf("."));
                    try {
     
                        Class tagetClaszz =Class.forName(rootPkg+"."+clazzName);
                        //判断类里面是否使用注解
                       if (tagetClaszz.isAnnotationPresent(Component.class)){
     
                           System.out.println(tagetClaszz);

                       }
                       //判断方法里面是否使用注解
                        Method[] methods = tagetClaszz.getMethods();
                        for (int i = 0; i <methods.length ; i++) {
     
                            if (methods[i].isAnnotationPresent(Auth.class)){
     
                                System.out.println(methods[i]);
                            }
                        }
                    } catch (ClassNotFoundException e) {
     
                        e.printStackTrace();
                    }
                }
            }


        }
    }
}

你可能感兴趣的:(反射,java,后端)