I\'m following this tutorial on Java annotaitons and implemented the Test annotation as shown there. But when running the code I get the following output.
java.l
The parameter that you pass to invoke
must be an object on which the method is invoked, unless the method is static
. What you did through reflection is equivalent to this:
MyTest obj = null;
obj.testBlah();
Naturally, there's an NPE. To fix this problem, pass an object on which to invoke the method, or make the method static
.
Here is one way to make a fix:
public void parse(Class clazz, T obj) throws Exception {
Method[] methods = clazz.getMethods();
int pass = 0;
int fail = 0;
for (Method method : methods) {
if (method.isAnnotationPresent(Test.class)) {
Test test = method.getAnnotation(Test.class);
Class expected = test.expected();
try {
method.invoke(obj);
pass++;
} catch (Exception e) {
if (Exception.class != expected) {
e.printStackTrace();
fail++;
} else {
pass++;
}
}
}
}
System.out.println("Passed:" + pass + " Fail:" + fail);
}
...
parser.parse(MyTest.class, new MyTest());
Demo on ideone.