[jboss-user] [Javassist] - Adding interface to an existing class
mnrz
do-not-reply at jboss.com
Mon Jun 6 00:08:09 EDT 2011
mnrz [http://community.jboss.org/people/mnrz] created the discussion
"Adding interface to an existing class"
To view the discussion, visit: http://community.jboss.org/message/608679#608679
--------------------------------------------------------------
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?
--------------------------------------------------------------
Reply to this message by going to Community
[http://community.jboss.org/message/608679#608679]
Start a new discussion in Javassist at Community
[http://community.jboss.org/choose-container!input.jspa?contentType=1&containerType=14&container=2062]
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.jboss.org/pipermail/jboss-user/attachments/20110606/c5dfa734/attachment.html
More information about the jboss-user
mailing list