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();
                    }
                }
            }


        }
    }
}

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值