If I have a Class instance at runtime, can I get its byte[] representation? The bytes I'm interested in would be in the Class file format, such that they'd be valid input to [ClassLoader.defineClass][3].
[3]: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ClassLoader.html#defineClass(java.lang.String, byte[], int, int)
EDIT: I've accepted a getResourceAsStream answer, because it's very simple and will work most of the time. ClassFileTransformer seems like a more robust solution because it doesn't require that classes be loaded from .class files; it would handle network-loaded classes for example. There's a few hoops to jump through with that approach, but I'll keep in in mind. Thanks all!
Serialization is the process of converting Java objects into a stream of bytes. The stream of bytes can be transmitted through a network connection, stored in a database as a BLOB object or saved as a binary file. The stored or transmitted stream of bytes can be reconstructed to Java object later.
Byte class is a wrapper class for the primitive type byte which contains several methods to effectively deal with a byte value like converting it to a string representation, and vice-versa. An object of Byte class can hold a single byte value. Byte class offers four constants in the form of Fields.
The ByteArrayOutputStream class of the java.io package can be used to write an array of output data (in bytes). It extends the OutputStream abstract class. Note: In ByteArrayOutputStream maintains an internal array of bytes to store the data.
The byteValue() method of Integer class of java. lang package converts the given Integer into a byte after a narrowing primitive conversion and returns it (value of integer object as a byte).
You can usually just load the class as a resource from the Classloader.
Class c = ... String className = c.getName(); String classAsPath = className.replace('.', '/') + ".class"; InputStream stream = c.getClassLoader().getResourceAsStream(classAsPath);
I would probably recommend using something from Apache commons-io to read the InputStream into a byte[]
, but IOUtils.toByteArray()
should do the trick. Writing that code is really easy to get wrong and/or make slow.
In general you can't go back like that. However, for some class loaders you may be able to get the resource file be taking the fully qualified class name, replacing .
with /
and appending .class
(so mypackage.MyClass
becomes mypackage/MyClass.class
(remember, may be case sensitive)).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With