convert Class object to bytes

Brian Harris picture Brian Harris · Jan 10, 2010 · Viewed 14.8k times · Source

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!

Answer

Alex Miller picture Alex Miller · Jan 10, 2010

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.