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