(1)示例包结构:
----controller
--------test1
------------test2
----------------Test2.java
----AnnoOne
----AnnoTwo
----PackageScanner
(2)注解
AnnoOne:
package controller;
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 AnnoOne {
String[] value();
}
AnnoTwo:
package controller;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
a
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface AnnoTwo {
String[] hello();
}
Test2:
package controller.test1.test2;
import controller.AnnoTwo;
import controller.AnnoOne;
@AnnoOne({"controller","AnnoOne","hello world"})
@AnnoTwo(hello = {"controller.AnnoTwo","hello kitty"})
public class Test2 {
public void sayName () {
System.out.println("this is file test2.");
}
}
(3)扫包代码
public class PackageScanner {
public static void getAnnoValByClass (String packageName,Class annoClass) throws ClassNotFoundException, InvocationTargetException, IllegalAccessException {
//注意创建的文件必须与包名对映上
String path = Thread.currentThread().getContextClassLoader().getResource("").toString().substring(6);
String pathName = path + packageName.replaceAll("\\.","/");
File file = new File(pathName);
scan(file,packageName,annoClass);
}
//扫包,并拼接成类路径格式
private static void scan (File file,String packageName,Class annoClass) throws ClassNotFoundException, InvocationTargetException, IllegalAccessException {
if(file == null)return;
if(file.isDirectory()){
File[] files = file.listFiles();
for (File file1 : files) {
scan(file1,packageName + "." + file1.getName(),annoClass);
}
}else{
String fullName = packageName;
//将.class文件抽离出来
if(fullName.endsWith(".class")){
fullName = fullName.substring(0,fullName.lastIndexOf("."));
//根据注解类,获取注解中携带的所有参数
String[] values = getAnnoValues(fullName,annoClass);
if(values != null){
for (String value : values) {
//write annotation handler code here...
System.out.println(value);
}
}
}
}
}
//只简单的获取返回值类型为String[]的注解并获取所有值
//可以根据需要定制想要的结果
private static String[] getAnnoValues (String fullName,Class annoClass) throws ClassNotFoundException, InvocationTargetException, IllegalAccessException {
Class clazz = Class.forName(fullName);
Annotation annotation = clazz.getDeclaredAnnotation(annoClass);
String[] values = null;
if(annotation != null){
Method[] methods = annoClass.getDeclaredMethods();
for (Method method : methods) {
if(method.getReturnType() == String[].class){
values = (String[])method.invoke(annotation);
}
}
}
return values == null ? null : values;
}
public static void main(String[] args){
getAnnoValByClass("controller.test1.test2",AnnoOne.class)
//输出:"controller","AnnoOne","hello world"
}
}
时时勤练练,不然久了就容易忘~~~~