1 Reply Latest reply on Apr 29, 2012 3:09 PM by jtahlborn

    Invoke Custom Defined Annotation called NotNull.

      I have created my own custom annotation called NotNull which should display the message "Value must not be null" when used in a method.
      How should I allow this annotation to be invoked if I pass a null value to a method (which should print the message "Value must not be null")

      For example: If I pass the value of null to method testNotNull(null), the annotation should kick in.
      ie How do I become an annotation consumer?


      import java.lang.annotation.Documented;
      import java.lang.annotation.ElementType;
      import java.lang.annotation.Retention;
      import java.lang.annotation.RetentionPolicy;
      import java.lang.annotation.Target;
      @Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE})
      @interface NotNull {
          String value() default "";
          String message() default "Value must not be null.";
      public class NotNullAnnotation_Test {
           public static void main(String[] args) {
                 testNotNull("Testing Not Null Annotation");
           static void testNotNull(@NotNull String str){
        • 1. Re: Invoke Custom Defined Annotation called NotNull.
          if you want the annotation to be applied at runtime, you will need to generate some code based on your annotation. the simpler way would be to write some sort of compile time annotation processor which either modifies the code before compilation or modifies the byte code. alternately, you could take the harder approach and do some sort of runtime code manipulation, but that's an order of magnitude more difficult that making the changes at compile time. there are a variety of existing projects out there which can help you do this, but you need to provide a few more details as to what, specifically, you are trying to accomplish.