自定义Annotation

来源:互联网 发布:淘宝宝贝怎么靠前 编辑:程序博客网 时间:2024/05/29 17:39
package com.test.javaSe01;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.reflect.Method;@Retention(value = RetentionPolicy.RUNTIME)// 此句必须有//\u6B64\u53E5\u5FC5\u987B\u6709@interface MySelfAnnotation {public int age() default 23;public String name() default "ctl";}@MySelfAnnotation(age = 100, name = "蔡腾林")class Person {int age;String name;public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int hashCode() {return super.hashCode();}@MySelfAnnotation(age = 230, name = "ctllin")public String toString() {return this.name + " " + this.age;}@MySelfAnnotationpublic void print() {}}/** *  * @author Administrator * @deprecated 获取自定义Annotation中的值 自定义的Annotation分别定义到类和方法上 */public class SelfAnnotationTestDemo {public static void main(String[] args) {SelfAnnotationTestDemo sa = new SelfAnnotationTestDemo();Class<?> c = null;try {c = Class.forName("com.test.javaSe01.Person");if (c.isAnnotationPresent(MySelfAnnotation.class)) {MySelfAnnotation ma = c.getAnnotation(MySelfAnnotation.class);System.out.println(ma.name() + " " + ma.age());}} catch (ClassNotFoundException e) {System.err.println("com.test.javaSe01.Person没有找到");e.printStackTrace();}Method method = null, method1 = null;try {method = c.getMethod("toString");System.out.println(method);method1 = c.getMethod("print");System.out.println(method1);} catch (SecurityException e) {e.printStackTrace();} catch (NoSuchMethodException e) {e.printStackTrace();}if (method.isAnnotationPresent(MySelfAnnotation.class)) {MySelfAnnotation myAnnotation = method.getAnnotation(MySelfAnnotation.class);int age = myAnnotation.age();String name = myAnnotation.name();System.out.println(name + " " + age);}if (method1.isAnnotationPresent(MySelfAnnotation.class)) {MySelfAnnotation myAnnotation = method1.getAnnotation(MySelfAnnotation.class);int age = myAnnotation.age();String name = myAnnotation.name();System.out.println(name + " " + age);}}}

0 0
原创粉丝点击