【发布时间】:2016-10-13 13:09:23
【问题描述】:
以下示例仅在公开时运行MyClass#myMethod()。如果它是私有的,它不会运行它。
私下怎么跑?
import org.apache.commons.lang3.reflect.MethodUtils;
import javax.annotation.PostConstruct;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Created by dims on 13.10.2016.
*/
public class CallPrivateMethodTest {
@Retention(RUNTIME)
@Target(METHOD)
public @interface MyAnnotation {
}
public static class MyClass {
@MyAnnotation
private void myMethod() {
System.out.println("myMethod() ran");
}
}
public static void main(String[] args) {
MyClass myObject = new MyClass();
List<Method> methods = MethodUtils.getMethodsListWithAnnotation(myObject.getClass(), MyAnnotation.class);
for(int i=0; i<methods.size(); ++i) {
try {
methods.get(i).invoke(myObject);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
【问题讨论】:
标签: java reflection annotations private-members