Given that class loaders accept to take as input a byte array of a given class, returning a Class>
, I wonder whether it is possible to do the reverse, t
No standard way I know of. But you might implement your own delegating classloader, keeping track of classes loaded in terms of name and bytecode.
What would be your use case? - Transferring code to a remote application?
You can use ClassLoader.getResourceAsInputStream() however it is not guaranteed this will be the same bytes as that which was loaded. I don't believe the actual bytes loaded are stored anywhere.
A ClassLoader
implementation must grok the representation of a class for the Java Language Specification version it supports. So it has to contain the logic to take a byte array and turn this into a Class
object, or extend some ClassLoader that does. However, the abstract ClassLoader
class that Java defines doesn't have any method that can return a byte[] from a Class. It is possible that some implementations have this (perhaps the bootstrap, system or other class loader), but that'd be implementation-specific at best and not something to rely on.
If you require this kind of functionality, one way to do it would be to create your own ClassLoader
implementation and override the defineClass
methods in such a way that the input byte arrays are mapped to Class
objects so they can later be retrieved.
Since a compiler turns source code into class files (basically the byte[]) and a class loader turns class files into Class
objects, there's nothing in the chain that's directly suitable to go from Class
to a byte[]. But with the stuff out there that does byte code weaving, runtime byte code generation and the like, you might find something that can do this.
Here's something to try with BCEL:
JavaClass clazz = Repository.lookupClass("foo.bar.YourClass");
byte[] bytes = clazz.getBytes();
I didn't know the answer prior to reading your question, but I knew I should check the following libraries, because they support the Java class file format:
If the above doesn't work, look for something else in these libraries.