java自定义注解有什么作用

如题所述

第1个回答  2017-04-24
自定义注解,可以应用到反射中,比如自己写个小框架。
如实现实体类某些属性不自动赋值,或者验证某个对象属性完整性等
本人自己用过的验证属性值完整性:
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface IgnoreProperty {
}
然后实体类中:
public class TarResearch implements Serializable{

@IgnoreProperty
private static final long serialVersionUID = 1L;

@IgnoreProperty
private Integer researchId;

@IgnoreProperty
private TarUser userId;

private String version;

private String grade;
....
}

然后action类中
// 验证数据完整性

Class userClass = TarResearch .class;

Field[] field = userClass.getDeclaredFields();

for (int i = 0; i < field.length; i++) {

if (field[i].getAnnotation(IgnoreProperty.class) != null) {

continue;

}

String fie = field[i].getName().substring(0, 1).toUpperCase()

+ field[i].getName().substring(1);

Method method = userClass.getMethod("get" + fie);

Object obj = method.invoke(u);

if (obj == null) {

sendResponseMsg(response, "数据错误");

return null;

}

}