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());
}
}
}
本文介绍了一种使用Java注解的方式来进行类级别的标记以及参数字段的注释。通过自定义注解`@Element`和`@MyParam`,实现了对类`Boy`的元数据存储,并在运行时通过反射读取这些注解信息。
721

被折叠的 条评论
为什么被折叠?



