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

后端 未结 4 1308
栀梦
栀梦 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: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.

提交回复
热议问题