我在这里看到2个解决方案:
- 通过条件检查执行此操作
public Clazz {
//private static boolean check = false; // if you want your method to be run once per class
private boolean check = false; // if you want your method to be run once per class instance
public void c() {
if(check) {
return;
}
check = true;
....
}
- 通过拦截方法调用(例如 Java 动态代理、javassist、asm 等)或使用 AOP 来做到这一点
但是你必须有一个接口:
public class TestInvocationHandler implements InvocationHandler {
//private static boolean check = false;
private boolean check = false;
private Object yourObject;
public TestInvocationHandler(Object object) {
yourObject = object;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if(check) {
return null; // or whatever you need
}
check = true;
return method.invoke(yourObject, args);
}
}
然后你会像这样创建你的对象:
ObjectInterface i = (ObjectInterface) Proxy.newProxyInstance(ObjectInterface.class.getClassLoader(),
new Class<?>[] {ObjectInterface .class},
new TestInvocationHandler(new MyImplementingClass()));