上一篇博客中讲解了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());
}
}
}