1,编写注解类
import java.lang.annotation.Documented;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Description {
public String value();
}
2,扫描指定包下的所有.class结尾的类
static List<String> list = new ArrayList<String>();
static String packageDirName = "com.space".replace('.', '/');
static StringBuffer buffer = new StringBuffer("com.space");
public static void main(String[] args) throws IOException, ClassNotFoundException {
Enumeration<URL> dirs=Thread.currentThread().getContextClassLoader().getResources(packageDirName);
while(dirs.hasMoreElements()){
URL url = dirs.nextElement();
String protocol = url.getProtocol();
if ("file".equals(protocol)){//文件扫描
String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
File file = new File(filePath);
getClassName(file);
}
if ("jar".equals(protocol)) {
JarFile jar= ((JarURLConnection) url.openConnection()).getJarFile();
Enumeration<JarEntry> entries = jar.entries();//获取文件,需要递归处理文件夹
}
}
for(String str:list){
System.out.println(str);
Class<?> c = Class.forName(str);
boolean isAnno = c.isAnnotationPresent(Description.class);
if(isAnno){
Description d = c.getAnnotation(Description.class);
System.out.println(d.value());
}
}
}
public static void getClassName(File file) throws IOException{
if(file.isDirectory()){
File[] files =file.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.getName().endsWith(".class")||pathname.isDirectory();
}
});
for(File f:files){
getClassName(f);
}
}else{
String name =file.getAbsolutePath();
name = name.substring(name.lastIndexOf("com\\space")).replaceAll("\\\\", ".");
name = name.substring(0, name.lastIndexOf("."));
list.add(name);
}
}
如果大家有更好的办法可以相互学习下