convert Class object to bytes

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