File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Can I re-define class bytes in ClassLoader (not changing interface)? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Can I re-define class bytes in ClassLoader (not changing interface)?" Watch "Can I re-define class bytes in ClassLoader (not changing interface)?" New topic
Author

Can I re-define class bytes in ClassLoader (not changing interface)?

Robert Paris
Ranch Hand

Joined: Jul 28, 2002
Posts: 585
Let's say i have a class:

And it's been defined by the classloader and we're in runtime, when I decide i want to add some System.out.println( ... ) calls to it (for whatever reason, but I want to do it at RUNTIME). So I use BCEL (or whatever) and create the bytes for the statement, then get the bytes of the class and add the statement in to the method bytes (and alter for size, stack, etc) but keep the interface the same. Is this possible? What would the repercussions/possible problems be? (And I'm assuming I can make my own classloader)
Robert Paris
Ranch Hand

Joined: Jul 28, 2002
Posts: 585
Well, it turns out that you can, BUT if you do then other classes will throw a ClassCastException when they try to use the new class. So whatever you want to do HAS to be done either at first loading/defining or you need to code ONLY to the interface AND load it ONLY explicitly (like Class.forName), thus only referencing the interface name. Then you can have something change the bytes, make a new class and return that and you'll still have the same interface. But of course, this means people might still be using the old version.
 
 
subject: Can I re-define class bytes in ClassLoader (not changing interface)?
 
Threads others viewed
how can i get the referance of the abstract class
Class serialization
Writing Plug-Ins (Not web)
ClassCastException ?
classloader
Two Laptop Bag

cast iron skillet 49er

more from paul wheaton's glorious empire of web junk: cast iron skillet diatomaceous earth rocket mass heater sepp holzer raised garden beds raising chickens lawn care CFL flea control missoula heat permaculture