This discussion is archived
1 Reply Latest reply: Apr 29, 2012 8:09 AM by jtahlborn RSS

Invoke Custom Defined Annotation called NotNull.

AjayL Newbie
Currently Being Moderated
Folks,
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?

Thanks,


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;
 
@Documented
@Retention(RetentionPolicy.RUNTIME)
@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){
          System.out.println(str.length());
     }

}
.
  • 1. Re: Invoke Custom Defined Annotation called NotNull.
    jtahlborn Expert
    Currently Being Moderated
    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.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points