例子一
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>0.10.2</version>
</dependency>
package com.chinaunicom.cnaps.test;
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 pay {
int garid();
}
package com.chinaunicom.cnaps.test;
import org.reflections.Reflections;
import java.util.Set;
@pay(garid = -1)
public class TestMain {
static {
System.out.println("什么时候执行");
Reflections reflections = new Reflections("com.chinaunicom.cnaps.test");
Set<Class<?>> classSet = reflections.getTypesAnnotatedWith(pay.class);
for (Class clazzSet: classSet){
pay pay = (pay) clazzSet.getAnnotation(pay.class);
System.out.println(pay.garid());
System.out.println(clazzSet.getCanonicalName());
try {
Class cls = Class.forName(clazzSet.getCanonicalName());
TestMain testMain = (TestMain) cls.newInstance();
testMain.test();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
System.out.println("1`1111");
}
public void test(){
System.out.println("到此一游");
}
}
例子二
package com.shiro.test.inter;
import java.lang.annotation.*;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface TypeAnnotation {
String value() default "Is-TypeAnnotation";
String name() default "我不是田哥";
}
package com.shiro.test.inter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
public class TestMain {
public static void main(String[] args) throws Exception {
TypeAnnotation typeAnno = Worker.class.getAnnotation(TypeAnnotation.class);
System.out.println("@TypeAnnotation值:" + typeAnno.name());
FiledAnnotation filedAno = Worker.class.getDeclaredField("myfield").getAnnotation(FiledAnnotation.class);
System.out.println( "属性名称:" + Worker.class.getDeclaredField("myfield").getName());
System.out.println("属性注解值FiledAnnotation = " + filedAno.value());
MethodAnnotation methodAnno = Worker.class.getMethod("getDefineInfo").getAnnotation(MethodAnnotation.class);;
System.out.println( "方法名称:getDefineInfo");
System.out.println("方法上注解name = " + methodAnno.name());
System.out.println("方法上注解url = " + methodAnno.url());
}
}