java中註解例子,使用反射做測試
阿新 • • 發佈:2019-01-02
上一篇部落格中講解了java中註解如何工作的,這章主要講解自定義註解的例子。
此例子中有三個檔案User.java、FieldAnnotation.java、FieldAnnotationTest.java,下面直接上原始碼。
/** * */ package com.test.annotations; public class User { private int id; private String name; private int age; private String country; public User(int id, String name, int age, String country){ this.id = id; this.name = name; this.age = age; this.country = country; } public int getId() { return id; } public void setId(int id) { this.id = id; } 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; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } }
package com.test.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Documented @Target(value = { ElementType.FIELD,ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) public @interface FieldAnnotation { public int id() default 1; public String name() default "zhangsan"; public int age() default 18; public String country() default "china"; }
/** * */ package com.test.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Target; import java.lang.reflect.Field; public class FieldAnnotationTest { //註解的使用 @FieldAnnotation(id = 2014, name = "james", age = 20, country = "usa") public Object obj; public User user; public static void main(String[] args) throws Exception { Field objField = FieldAnnotationTest.class.getField("obj"); FieldAnnotation fa = objField.getAnnotation(FieldAnnotation.class);// 得到註解,起到了標記的作用 System.out.println("-----------obj-------------------"); System.out.println(fa.id() + "," + fa.name() + "," + fa.age() + "," + fa.country()); System.out.println("-----------obj-------------------"); //把註解中值賦給user物件 FieldAnnotationTest tm = new FieldAnnotationTest(); Field userField = FieldAnnotationTest.class.getField("user"); userField.set(tm, new User(fa.id(),fa.name(),fa.age(),fa.country())); System.out.println("-----------user-------------------"); System.out.println(tm.user.getId() + "," + tm.user.getName() + "," + tm.user.getAge() + "," + tm.user.getCountry()); System.out.println("-----------user-------------------"); //註解能獲得註解自己的註解 Target t = fa.annotationType().getAnnotation(Target.class); ElementType[] values = t.value(); for(ElementType etype:values){ System.out.println(etype.toString()); } } }