0

There is a class which's method returns result with delegate pattern.

class A {

   interface ICallback {
     callback(String data);
   }

   void doSomeAction(ICallback cb) {
     //some manipuation
     if(cb != null) {
        cb.callback(response);
     }
  }
}

The problem here is that A class is in library project and it possible that library will not be attached to the main project. So, the load of A class and call of doSomeAction should be implemented with reflections. But how should proceed with callback? I read about Proxy, but I am still can not understand is it possible to solve it with Porxy. Or is there other solutions for such case?

I tried with Proxy:

        Class<?> clazz = Class.forName("com.aa.bb.cc.dd.A$ICallback");
        Class<?>[] interfaces = new Class[] { clazz};
        Object proxy = Proxy.newProxyInstance(clazz.getClassLoader(), interfaces, handler);

In the last line I am gettin "com.sun.jdi.InvocationException occurred invoking method" error.

someUser
  • 965
  • 12
  • 24
  • You mean cb.callback(response), right? – Oleg Gryb Jun 22 '14 at 18:51
  • @OlegGryb Yes, I'v just edited. thanks! – someUser Jun 22 '14 at 18:55
  • Where implementation of ICallback should be? Is it in the library that is not in the project or in the project? Can you take the interface out of class A and put it to a separate ICallback.java file? – Oleg Gryb Jun 22 '14 at 19:00
  • the callback should be in project. No, it's a library and I can not change it. – someUser Jun 22 '14 at 19:02
  • Using `java.lang.reflect.Proxy` is the right solution. Tutorial: http://tutorials.jenkov.com/java-reflection/dynamic-proxies.html – HHK Jun 22 '14 at 19:11
  • Suppose you can create the proxy, and you can cast it to `ICallback`. How are you going to pass the proxy to `A.doSomething` method? – fajarkoe Jun 22 '14 at 19:49
  • You'll need to post your handler. Here is a good example: http://stackoverflow.com/questions/1082850/java-reflection-create-an-implementing-class – Oleg Gryb Jun 22 '14 at 19:54
  • it works,thanks for your attention. I will complete and past the code. – someUser Jun 22 '14 at 20:06

0 Answers0