问题描述
我是Java Annotation
的新手,一直在寻找同时在多个变量上应用单个annotation
的情况.
I am rookie in Java Annotation
and have been searching for applying single annotation
on multiple variable simultaneously.
@Document(collection = "users")
public class User {
private ObjectId id;
@NotNull
private String email;
private String imageURL;
private String authToken;
private Date createdDate;
private Date updateDate;
private boolean isActivated;
private int credits;
.....getter/Setter Method
我也想在email
,imageURL
和authToken
上应用@NotNull
属性.我可以通过将@NotNull
写入每个variable
来做到这一点,但不建议这样做.怎么做?
I want to apply @NotNull
property on email
, imageURL
and authToken
too. I can do it by writing @NotNull
to each variable
but not preferring. How to do it?
推荐答案
@NotNull注释可以应用于元素而不是元素组.
@NotNull annotation can be applied at element not at group of elements.
如果您真的想摆脱样板代码,可以使用Lombok之类的框架,在一定程度上可以为您提供帮助.
If you really want to get away with boiler plate code, you can use frameworks like Lombok which can help you to certain extent.
链接: http://projectlombok.org/features/Data.html
或者您可以使用反射来验证所有方法.
OR you can use reflection to validate all the method.
for (Field f : obj.getClass().getDeclaredFields()) {
f.setAccessible(true); // optional
if (f.get(obj) == null) {
f.set(obj, getDefaultValueForType(f.getType()));
// OR throw error
}
}
这篇关于如何在多个变量上应用单个注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!