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

时间:2018-03-14 21:54:12

标签: java

我已经实现了名为ClientContainerInvocationHandler的代理。它用于我的类SocketContainer的对象,它们实现了具有方法IClient的接口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)

1 个答案:

答案 0 :(得分:1)

我认为你在找这样的东西?:

@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);
    }