//Almost always RUNTIME
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@interface MyTest {}
class Sample{
@MyTest
public static void m1(){}
}
public class MyAnnotation{
public static void main(String[] args){
Class testClass = Sample.class;
//Get all methods including private, protected
//as opposed to testClass.getMethods() only returning public methods
for (Method m : testClass.getDeclaredMethods()){
if (m.isAnnotationPresent(MyTest.class)){
try{
m.invoke(null); //Call static method
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
Thursday, 24 November 2016
Effective Java Item 35. Write own annotation and reflection
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment