java 注解
程序员文章站
2022-06-17 13:09:36
...
public @interface MyAnno {
}
public @interface MyAnno2 {
public String schoolName();
}
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnno3 {
public String schoolName() default "城市学院";
}
@MyAnno
public class Demo {
//注解中若包含成员方法(变量)且无默认值,则必须赋值
@MyAnno2(schoolName="hncu")
private String name;
@MyAnno3(schoolName="hncu")
private int age2;
@MyAnno
public void t1(){
System.out.println("11111111111");
}
}
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Inherited
@Documented
@Retention(RetentionPolicy.RUNTIME) //小心: 必须声明成RUNTIME,我们的程序才能识别MyAnno4注解
@Target({ElementType.TYPE,ElementType.METHOD})
public @interface MyAnno4 {
}
import java.lang.reflect.Method;
import cn.hncu.annotation.MyAnno3;
@MyAnno3(schoolName = "aaa")
public class Demo {
// @MyAnno4
private String id;
@MyAnno4
public void t1() {
System.out.println("111111111111");
}
public static void main(String[] args) throws Exception {
// 注解存在于class文件中,因此要通过类反射才能读取出来
Class c = Class.forName("cn.hncu.annotation.v2.Demo");
// 判断c中是否存在注解MyAnno4.class---注意,这只是判断类上是否有注解,Field和Method上的不算
boolean boo = c.isAnnotationPresent(MyAnno4.class);
// c.isAnnotation(); //判断c本身是否是一个注解
// c.getAnnotations();//获得c中的所有注解
System.out.println(boo);
Method m = c.getDeclaredMethod("t1", null);
boo = m.isAnnotationPresent(MyAnno4.class);// 判断方法m上是否有指定注解
System.out.println("boo2:" + boo);
// 读取注解中的成员,以当前类上的@MyAnno3注解为例
boolean flag = c.isAnnotationPresent(MyAnno3.class);
if (flag) {
MyAnno3 annoObj = (MyAnno3) c.getAnnotation(MyAnno3.class);
String name = annoObj.schoolName(); // 读取成员
System.out.println("name:" + name);
}
}
}