-
1. Re: Remove an interface from a Class
megalodon Feb 25, 2010 2:44 AM (in response to kevinkilroy)How I approached this:
I obtained the list of interface CtClasses using CtClass.getInterfaces();
I removed the Interface I chose from the list of CtClasses. Then I applied the filtered list of interfaces onto the CtClass using CtClass.setInterfaces() and passed in the filtered CtClass Array of Interfaces to that method. Tested this with a simple example.
-
2. Re: Remove an interface from a Class
kevinkilroy Feb 25, 2010 5:05 AM (in response to megalodon)Hi,
Could you provide an example please? I'm receiving the following exception:
java.lang.LinkageError: loader (instance of sun/misc/Launcher$AppClassLoader): attempted duplicate class definition
With this code:
ClassPool pool = ClassPool.getDefault();
CtClass cc = pool.get("com.northwales.ilm.domain.ContextBarItem");
CtClass[] ifs = cc.getInterfaces();
CtClass[] newIfs = new CtClass[1];
newIfs[0] = ifs[0];
cc.setInterfaces(ifs);
cc.writeFile();
Class newClass = cc.toClass();
ContextBarItem cbi = (ContextBarItem)newClass.newInstance();Thanks!
Kevin.
-
3. Re: Remove an interface from a Class
megalodon Feb 25, 2010 6:35 AM (in response to kevinkilroy)Hello,
I do not think there should be anything wrong with the interface-removing part. You can verify this by printing the interface class names before and after you change them, if you need. I can think of 2 possibilities for the exception:
I would put my money on this one:
1. You are trying to modify a class that has already been loaded. This is not allowed by the JVM. You might have seen this thread in a forum that posts your same error: http://lists.jboss.org/pipermail/jboss-user/2009-March/152559.html. You might want to modify your class during load time in this case using a javaagent and classfiletransformer (or some other approach).
2. You might need a different context class loader to load the ContextBarItem class. The default CtClass.toClass() uses the context class loader of the current thread. You could use an overloaded Class:
public java.lang.Class toClass(java.lang.ClassLoader loader, java.security.ProtectionDomain domain)
throws CannotCompileException
suppose the object of ContextBarItem class is myCBI,Class newClass = cc.toClass(myCBI.getClass().getClassloader(), myCBI.getClass().getProtectionDomain());
Check out http://www.csg.is.titech.ac.jp/~chiba/javassist/tutorial/tutorial.html#toclass and Javassist API for more details. I'm not too clear on these concepts either.
-Arvind