ElementType RetentionPolicy可以查看这两个枚举的API
package yan;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
public class w {
public static void main(String[] args) throws Exception {
Class<?> forName2 = Class.forName("yan.Anntext");//填写反射获取的类
boolean annotationPresent = forName2.isAnnotationPresent(Des.class);//判断是否有isAnnotationPresent的注解
if(annotationPresent){//如果有
Des ds=(Des) forName2.getAnnotation(Des.class);//就获得Des注解
System.out.println(ds.value());//打印value值
Method[] declaredMethods = forName2.getDeclaredMethods();//然后通过forName2获取全部方法
for(Method d:declaredMethods){//便利方法
if(d.isAnnotationPresent(Author.class)){//判断方法中是否含有Author注解
Author annotation = d.getAnnotation(Author.class);//有获取
System.out.println(annotation.name()+annotation.group());//打印
}
}
}
}
}
@Target(ElementType.METHOD)//用于表示在那个位置
@Retention(RetentionPolicy.RUNTIME)//用于表示在那个时间段
@Documented//生成注解
@interface Author{
String name();
String group();
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@interface Des{
String value();
}
@Des("这是第二个接口")//因为定义的是value值所以可以直接填写
class Anntext{
@Author(name="杨承龙",group="我去看看")
public void test(){
System.out.println("阿斯蒂芬");
}
}