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
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.