2

I am rookie in Java Annotation and have been searching for applying single annotation on multiple variable simultaneously.

Code:

@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

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?

Community
  • 1
  • 1
Amit Pal
  • 10,604
  • 26
  • 80
  • 160

2 Answers2

1

@NotNull annotation can be applied at element not at group of elements.

JavaDoc: The annotated element must not be null. Accepts any type.

If you really want to get away with boiler plate code, you can use frameworks like Lombok which can help you to certain extent.

Link : 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
  }
}
Maas
  • 1,317
  • 9
  • 20
  • What about for other references like `@DBRef`? I also didn't find any information on it. – Amit Pal Aug 12 '14 at 10:23
  • I didn't get your question, can you elaborate 'What about for other references like @DBRef?' – Maas Aug 12 '14 at 10:32
  • As the blog stated that we can't apply `@NotNull` annotation on a group of Element. Does it only apply on `@NotNull` annotation or all of them? – Amit Pal Aug 12 '14 at 10:39
  • 1
    It applies to '@NotNull' annotation. As I know there is no annotation which can be applied on all declared fields as you are expecting. Hibernate validation is one matured validation framework you can look at: http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/ – Maas Aug 12 '14 at 10:45
1

Java does not support multiple annotation of this type. But you can write something like this

  • Create a class with annotated field.
  • Create setters and getters to access the field.
  • Create all your name,email field as instance of this class.

This way fields will implicitly annotated as NotNull.

            public class NotNullString {
                @NotNull
                String str;
                public void set(String str)
                {
                    this.str = str;
                }
                public String get()
                {
                    return this.str;
                }
            }

            NotNullString name;
            NotNullString email;
mirmdasif
  • 6,014
  • 2
  • 22
  • 28