Converting a given class (let's say, java.lang.Object) to a byte array. Is it possible?

后端 未结 4 1307
栀梦
栀梦 2021-01-13 17:13

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

相关标签:
4条回答
  • 2021-01-13 17:29

    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?

    0 讨论(0)
  • 2021-01-13 17:33

    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.

    0 讨论(0)
  • 2021-01-13 17:49

    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.

    0 讨论(0)
  • 2021-01-13 17:52

    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:

    • BCEL
    • javassist
    • asm

    If the above doesn't work, look for something else in these libraries.

    0 讨论(0)
提交回复
热议问题