kofucii
kofucii

Reputation: 7663

Read a line of code from class file

Given a StackTraceElement.getLineNumber(), is there a way to read the content of this line from a compiled class file? And even if it is possible to match the line, would the content of the class file will be "obfuscated" by the compiler?

For example if I had:

public void myMethod () {
    MyObj m = new MyObj ();   // can I reconstruct this line as String?
}

Upvotes: 0

Views: 689

Answers (3)

Grundlefleck
Grundlefleck

Reputation: 129385

You could retrieve the bytecode instructions from the class file (Foo.class), but not the String that represents the source code. However, given a source file and a line number, you could instead read the line from the source file (Foo.java), using standard file reading techniques.

To get an idea of the kind of information contained in a .class file, check out the javap tool. I suppose technically you could make a best guess at the source that compiled to that class, or run a decompiler on it, but line numbers won't match exactly, formatting would be totally different, and perhaps crucially, there would be no comments or annotations using source retention level.

Upvotes: 1

Peter Szanto
Peter Szanto

Reputation: 7722

you can include the source file into your war / jar file which you can read as a file. The bytecode only contains the line number not the actual code

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1075765

The source code is not contained by the compiled class file, which contains bytecode; so no, working only from the class file you can't reconstruct that line of code. It's possible to de-compile Java bytecode, of course, and a sufficiently well-built decompiler might reconstruct that line of code to a greater or lesser extent, but you'd have to have a decent decompiler. The end results may or may not look much like the original source code, depending on optimisations and such.

Upvotes: 4

Related Questions