用Java捕获方法调用 [英] Capture method calls in Java
问题描述
我需要捕获Java中的方法调用,我不想使用JPDA或JDI;我希望它发生在原始的JVM中。
I need to capture a method call in Java and I do not want to use JPDA or JDI; I want it to happen in the original JVM.
例如:
public class A {
public void m() {}
}
public class Main {
public static void main(String[] args) {
A a = new A();
a.m();
}
}
我不想让方法在时间,但需要捕获它并将其安排在队列中。因此,AOP在这方面不会帮助我。我想过代理这个方法。例如:
I do not want to actually let the method execute at the time, but need to capture it and schedule it in a queue. Thus, AOP will not help me in this regard. I thought about proxying the method. Something such as:
public class A {
public void m() {
methodQueue.add(new MethodInvocation() {
public void invoke() {m_orig();}
});
}
private void m_orig(){}
}
有任何想法吗?非常感谢提前。
Any ideas? Thanks so much in advance.
推荐答案
您可以在Java中使用一种名为Dynamic Proxies的技术。它们在以下文档中有详细描述:动态代理
You can use a technique called Dynamic Proxies in Java. They are described in detail in the following document: Dynamic Proxies
您的问题的解决方案将是(需要进行少量更改):
The solution for your problem would then be (with little changes necessary):
public interface A { void m(); }
public class AImpl implements A { public void m() {} }
public class EnqueueProxy implements java.lang.reflect.InvocationHandler {
private Object obj;
public static Object newInstance(Object obj) {
return java.lang.reflect.Proxy.newProxyInstance(
obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(),
new EnqueueProxy(obj));
}
private EnqueueProxy(Object obj) {
this.obj = obj;
}
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
try {
MethodQueue mq = ... // get the queue from where you want
mq.add(new MethodInvocation(obj, m, args)
} catch (InvocationTargetException e) {
throw e.getTargetException();
} catch (Exception e) {
throw new RuntimeException("unexpected invocation exception: " + e.getMessage());
}
return null;
}
}
然后构造一个EnqueueProxy用于A接口的实现并调用m方法:
Then construct a EnqueueProxy for an implementation of the A interface and call the m method:
A a = (A) EnqueueProxy.newInstance(new AImpl());
a.m();
这篇关于用Java捕获方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!