Hi
I have a class which is in legacy system and we cannot change the class. I need to create a java proxy for that class but this is a class without interface. So I have created an interface and write the following code to add this interface to that class at runtime but the class.getInterfaces() method still returns no interface!
--
public class Main {
public static void main(String[] args) throws Exception {
//@SuppressWarnings("rawtypes")
createInterface();
AnAbstractClass instance = new AClassFromAbstract();//instance.getClass().getInterfaces()
Object proxy = Proxy.newProxyInstance(ProxyIntAnAbstractClass.class.getClassLoader(),
new Class[] {ProxyIntAnAbstractClass.class},
new MyInvocationHandler(instance));
ProxyIntAnAbstractClass instance2 = (ProxyIntAnAbstractClass) proxy;
instance2.doSomething();
instance2.doSomethingElse();
}
public static Class createInterface() throws Exception{
ClassPool pool = ClassPool.getDefault();
ClassPath cp = new ClassClassPath(AnAbstractClass.class);
pool.insertClassPath(cp);
pool.importPackage("com.macquarie.test.proxy");
CtClass myinterface = pool.get("com.mmm.test.proxy.ProxyIntAnAbstractClass");
CtClass tclass = pool.getCtClass("com.mmm.test.proxy.AnAbstractClass");
tclass.setInterfaces(new CtClass[] {myinterface});
tclass.rebuildClassFile();
tclass.detach();
return myinterface.toClass();
}
}
--
When I execute this code, since the ProxyIntAnAbstractClass is not interface of AnAbstractClass, InvocationHandler complains that the object is not an instance of declaring class
Can you please help me on this?