Search code examples
javadecompiler

How to dynamically decompile a Class Object on memory?


I'm making a tool to dynamically display the sourcecode of running java class. I need a tool to help me on dynamically decompile from a Class Object to String of sourcecode. I know some decompile tools like Jad, DJ decompiler can decompile a .class file but I expect a tool can:

Class<?> c = ..; // get from runtime environment
String sourcecode = **DecompileTool**.decompileClassObject(c);
return sourcecode;

I need such a DecompileTool, anyone knows? Thanks


Solution

  • I'm not aware of any decompiler that can be used like that.

    Indeed, in the general case it is not possible to implement a decompiler that works like that:

    • The Class<?> object that you get from the runtime doesn't provide any way to get to the bytecodes.

    • In order to get hold of the bytecodes, you would need to redo what the classloader does when it locates the ".class" file from the classpath.

    • I don't think there's a way to find out what classloaders are in use ... if you include the possibility of dynamically instantiated classloaders. (And such classloaders are normal practice in (for example) web containers.)

    • In the general case, a classloader will do that in ways that you cannot reproduce ... without reverse engineering and hard-coding the same logic into your decompiler adapter code.

    Besides, doing this on the fly is probably pointless, because there is a significant chance that the decompiler will produce source code that isn't compilable.