//注解的定义
//@Target,修饰所有能够修饰的东西 @Target({ElementType.TYPE,ElementType.METHOD,ElementType.FIELD}) //如果设置存活时间,默认只存活在原码阶段---->字节码 ---->运行期间 @Retention(RetentionPolicy.RUNTIME) //定义注解 public @interface Anno { int value(); int [] method(); String method1(); }
//使用注解
@Anno(value = 56 , method = 23,method1 = "我爱你") public class Person { @Anno(value = 66,method = 88,method1 = "真是一个阳光明媚的一天") private String name ; private int age; public Person() { } public Person(String name, int age) { this.name = name; this.age = age; } @Anno(value = 23,method = 34,method1 = "你看看哥哥够不够帅") public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } } //解析注解
publiclass Test { public static void main(String[] args) throws NoSuchFieldException, NoSuchMethodException { //获取字节码文件 Class<Person> personClass = Person.class; //类的注解解析 Anno annotation = personClass.getAnnotation(Anno.class); int[] method = annotation.method(); String s = annotation.method1(); int value = annotation.value(); System.out.println(Arrays.toString(method)); System.out.println(s); System.out.println(value); //成员变量的注解解析 Field name = personClass.getDeclaredField("name"); Anno annotation1 = name.getAnnotation(Anno.class); int[] method1 = annotation1.method(); String s1 = annotation1.method1(); int value1 = annotation1.value(); System.out.println(Arrays.toString(method1)); System.out.println(s1); System.out.println(value1); //成员方法的注解解析 Method getName = personClass.getDeclaredMethod("getName"); Anno annotation2 = getName.getAnnotation(Anno.class); int[] method2 = annotation2.method(); String s2 = annotation2.method1(); int value2 = annotation2.value(); System.out.println(Arrays.toString(method2)); System.out.println(s2); System.out.println(value2); } }