How to apply Single annotation on multiple variables?

前端 未结 2 1563
野性不改
野性不改 2021-01-21 14:09

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

Code:



        
相关标签:
2条回答
  • 2021-01-21 14:26

    @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
      }
    }
    
    0 讨论(0)
  • 2021-01-21 14:43

    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;
    
    0 讨论(0)
提交回复
热议问题