本文介绍了如何在多个变量上应用单个注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是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

我也想在emailimageURLauthToken上应用@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
  }
}

这篇关于如何在多个变量上应用单个注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 21:02