Search code examples
javajavac

How to make Java compiler generate line numbers in compiled code


I have a hello world program called A.class. It was compiled using command javac A.java. All it does is print "hello world".

Next, I compiled using javac -g A.java. I am expecting to see line numbers, but can't see. Any idea what happened?

I do see very minor differences in some kind of special characters between .class file of javac compiled, and javac -g compiled. But I can't see any line numbers.

My curiosity for this is because I want to find what kind of impact line numbers may have on performance. Second, I want to know how log4j etc maintain line numbers for logging. Thanks.


Solution

  • The compile command is good, -g turns on generation of debug information, indeed. BTW: line numbers are generated by default, need -g:none or similar to turn this off.

    What's missing is a way to meaningfully inspect the generated .class file, similar to how a tool would use it. Try:

    $ javap -l -c A.class
    

    -l turns on printing of line number tables. -c turns on printing of disassembled bytecode instructions (might be interesting since line number tables relate source line numbers to bytecode instructions).