Reputation: 25
Error when using my own annotations, can any one help mein this problem This is my following Annotation:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(value=ElementType.TYPE)
@Retention(value = RetentionPolicy.RUNTIME)
public @interface CanRun {
}
This is one of my class showing an error in the in place of annotation , can any one explain & solve...
import java.lang.reflect.Method;
public class AnnotationRunner {
public void method1() {
System.out.println("method1");
}
@CanRun
public void method2() {
System.out.println("method2");
}
@CanRun
public void method3() {
System.out.println("method3");
}
public void method4() {
System.out.println("method4");
}
public void method5() {
System.out.println("method5");
}
}
This is main class which uses this annotation
public class MyTest {
public static void main(String[] args) {
AnnotationRunner runner = new AnnotationRunner();
Method[] methods = runner.getClass().getMethods();
for (Method method : methods) {
CanRun annos = method.getAnnotation(CanRun.class);
if (annos != null) {
try {
method.invoke(runner);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
Upvotes: 2
Views: 210
Reputation: 7341
You need
@Target(value=ElementType.METHOD)
if you want to annotate methods
Upvotes: 2
Reputation: 2664
change
@Target(value=ElementType.TYPE)
to
@Target(value=ElementType.METHOD)
Upvotes: 6