Reputation: 81
I am new to Java and I have a Problem concerning Java Annotations. Short: The code works just fine, when I set @Target to "TYPE" and place the Annotation above the "SynCheck"-class. As soon as I change @Target to "METHOD" (as seen in the source code) and place the Annotation over the "isValid"-method, it causes a NullPointerException and I cannot figure out, why. Please have a look on the code. (It is kind of a email syntax validator).
Main.java:
package emailvalid;
import java.lang.annotation.Annotation;
public class Main {
public static void main(String[] args) throws Exception {
SynCheck validate = new SynCheck();
Class<? extends SynCheck> c = validate.getClass();
Annotation an = c.getAnnotation(InputVal.class);
InputVal s = (InputVal)an;
System.out.println(s.input());
System.out.println("Syntax: " + SynCheck.isValid(s.input()));
}
}
SynCheck.java:
package emailvalid;
import java.util.regex.Pattern;
public class SynCheck {
@InputVal(input = "[email protected]")
public static boolean isValid(String checkAddr)
{
final Pattern regexevalpat = Pattern.compile(
"^((?=.{1,63}$)[a-zA-Z0-9]+[a-zA-Z0-9\\.\\!\\#\\$\\%\\&\\’\\*\\+\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~\\-]{0,})@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*\\.[a-zA-Z0-9-]+$");
if (!regexevalpat.matcher(checkAddr).matches()) {
return false;
} else {
return true;
}
}
}
InputVal.java:
package emailvalid;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface InputVal {
String input();
}
What am I doing wrong?
Any help appreciated. Thank you.
Upvotes: 0
Views: 2041
Reputation: 21194
Your code does not look for the annotation on the method. Only on the class.
SynCheck validate = new SynCheck();
Class<? extends SynCheck> c = validate.getClass();
Annotation an = c.getAnnotation(InputVal.class);
InputVal s = (InputVal)an;
That will only work if the InputVal annotation is on the SyncCheck class (as a type annotation).
When you move the annotation to the method the annotation will be null as it's no longer on the class...
If you want to put it on the method you need to change your code to:
Class<? extends SynCheck> c = validate.getClass();
Method m = c.getMethod("isValid");
InputVal s = m.getAnnotation(InputVal.class);
A side comment is that you don't have to cast the annotation, you can retrieve it directly into the type it is.
Upvotes: 1