gpt4 book ai didi

java - 从代理调用方法调用另一个方法

转载 作者:行者123 更新时间:2023-11-30 06:15:32 25 4
gpt4 key购买 nike

我已经实现了名为ClientContainerInvocationHandler的代理。它用在我的类 SocketContainer 的对象上,该类实现了 IClient 接口(interface),该接口(interface)具有方法 public int getId()

现在我正在尝试调用代理下当前对象的方法,该方法的类型为 SocketContainer 我在下面的评论中显示的 getId() 方法(参见下面的代码)。这可能吗 ?

public class ClientContainerInvocationHandler implements InvocationHandler {

private final Object target;

private ClientContainerInvocationHandler(final Object object) {
this.target = object;
}

public static Object createProxy(final Object object) {
final Object proxy = Proxy.newProxyInstance(object.getClass().getClassLoader(), object.getClass().getInterfaces(), new ClientContainerInvocationHandler(object));
return proxy;
}

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("addMessage")) {
// invoke on the current object
// the method getID and retrieve the result here
// I have tried this :
// Method m =target.getClass().getMethod("getId");
// but I get exception if I do this
}
}
}

完全异常:

java.lang.reflect.UndeclaredThrowableException
at com.sun.proxy.$Proxy5.getID(Unknown Source)
at com.project.chat_system.ChatRoom.addClient(ChatRoom.java:18)
at com.project.chat_system_tests.RealTest.testMessagesReceived(RealTest.java:35)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)

...

Caused by: java.lang.NoSuchMethodException: com.project.chat_system.SocketContainer.getId()
at java.lang.Class.getMethod(Unknown Source)
at com.project.chat_system_tests.ClientContainerInvocationHandler.invoke(ClientContainerInvocationHandler.java:30)

最佳答案

我认为您正在寻找类似的东西?:

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("addMessage")) {
// invoke on the current object
//the method getID and retrieve the result here
Method getIdMethod = proxy.getClass().getMethod("getID");

//proxy is the object in which you want to call your method on
SomeResult result = getIdMethod.invoke(proxy);

//if you need to pass arguments
SomeResult result = getIdMethod.invoke(proxy, args);
}

关于java - 从代理调用方法调用另一个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49288229/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com