1 Reply Latest reply on Jun 7, 2011 12:03 AM by Mohammad Norouzi

    Adding interface to an existing class

    Mohammad Norouzi Novice



      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 {



              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;





          public static Class createInterface() throws Exception{

              ClassPool pool = ClassPool.getDefault();

              ClassPath cp = new ClassClassPath(AnAbstractClass.class);




              CtClass myinterface = pool.get("com.mmm.test.proxy.ProxyIntAnAbstractClass");



              CtClass tclass = pool.getCtClass("com.mmm.test.proxy.AnAbstractClass");

              tclass.setInterfaces(new CtClass[] {myinterface});



              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?