1、自定义注解
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;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD,ElementType.METHOD})
@Documented
public @interface FieldMeta {
String name() default "";
String description() default "";
}
2、实体类字段使用注解
public class Dog {
@FieldMeta(name="年龄",description="小狗的年龄")
private int age;
@FieldMeta(name="名称",description="小狗的名称")
private 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;
}
}
3、使用注解
public static void main(String[] args) {
Dog dog = new Dog();
Class<? extends Dog> objclass = dog.getClass();
Field[] at = objclass.getDeclaredFields();
for (Field fd : at) {
if (fd.isAnnotationPresent(FieldMeta.class)) {
FieldMeta d = fd.getAnnotation(FieldMeta.class);
System.out.println(d.name());
System.out.println(d.description());
}
}
}
4、打印结果
年龄
小狗的年龄
名称
小狗的名称