package package3;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//注解的注解
@Retention(RetentionPolicy.RUNTIME)
//表示注解试用的范围,此处是表示只用到变量上
@Target(ElementType.FIELD)
public @interface MyAnnotation {
String value() default ""; //注解的属性
}
package package3;
import java.lang.reflect.Field;
public class MyTest {
@MyAnnotation("zhangsna")
String s;
public static void main(String[] args) throws SecurityException, NoSuchFieldException {
Class clazz = MyTest.class;
Field fl = clazz.getDeclaredField("s");
//得到属性的注解
MyAnnotation mn = fl.getAnnotation(MyAnnotation.class);
System.out.println(mn.value());//得到注解的属性
}
}
时间: 2024-10-23 10:19:04