1.类级别
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Element {
int id();
String type();
}
2.参数字段
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyParam {
String paramName();
}
3.class
@Element(id = 1, type = “boy”)
public class Boy {
@MyParam(paramName = "name")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
4.测试类
public class Test {
public static void main(String[] args) {
Element loveElement = Boy.class.getAnnotation(Element.class);
System.out.println(loveElement.id());
System.out.println(loveElement.type());
Field[] fields = Boy.class.getDeclaredFields();
for (Field field : fields) {
MyParam myParam = field.getAnnotation(MyParam.class);
System.out.println(field.getName());
System.out.println(myParam.paramName());
}
}
}