Jason Perrone [
http://community.jboss.org/people/jasonperrone] created the discussion
"Newbie question: How do you modify class members?"
To view the discussion, visit:
http://community.jboss.org/message/596347#596347
--------------------------------------------------------------
Ok, I understand how to modify a class. I've obtained my CtClass from the ClassPool
and I added a new member. Great. What I don't understand is how to replace the old
version of this class in this ClassPool with the new version. This may be a basic
mis-understanding of the JVM on my part. My understanding is that once you load a class,
whether from a file or a class you constructed in the application, that that's it.
It's there and you can't get rid of it. So, if I have a class called Potato in
the ClassPool, and I get Potato:
CtClass ctClass = cp.get("Potato")
And then I add a member to this class. .. ctClass.addField(f);
I don't understand how to get the changed version of the class into the classpool.
After my change above, Potato in the classpool is not modified. I thought it would be.
But in reading about Javassist, it seems that you have to make a new class from the change
by calling toClass on CtClass, but I can't call toClass on the CtClass because a class
of that same name already exists in the ClassPool. Actually, the exact instructions from
JavaAssist are:
1) Get the class from the classpool
2) Modify it
3) Either use writeFile(not applicable to me) to call toByteCode to get the new class
definition. Ok, so I call toByteCode and get my new class definition (Potato with the new
field). I figured that I then need to call defineClass() on the ClassLoader with the new
byteCode but once again, the error that I can't compile the class because a class of
the same name already exists.
So, when it comes to modifying a class, are you ever actually modifying the original class
that was loaded, or are you just creating a new class that is cloned from the original
class and then applying some changes to it?
--------------------------------------------------------------
Reply to this message by going to Community
[
http://community.jboss.org/message/596347#596347]
Start a new discussion in Javassist Development at Community
[
http://community.jboss.org/choose-container!input.jspa?contentType=1&...]