How do I print the method body reflectively?

How do I add to the reflective nature of Java to print the method body?

With considerable difficulty, I’m afraid.

For a start, the original source code is most likely to be unavailable to a running program. As a rule, developers do not include source code in the binary JARs. (And even if they do, there is not guarantee that they will be the “real” sources.)

You can usually obtain the bytecodes for the class by translating the FQN for the class into the bytecode file and using the classes classloader to load the file as a resource stream. But it is not guaranteed that the bytecodes you get this way will be the same as what were loaded. (Some classloaders mess around with the bytecodes for various reasons.)

Assuming that you can get the real bytecodes, the last step will be to either display them raw, or disassemble or decompile them to something more readable. You should be able to use javap to do a disassembly, but decompilation would entail using a third party product. Of course, the decompiled code will look significantly different to the original code, and if the bytecodes have been obfuscated they source code will be pretty much unreadable.

Leave a Comment