I have a line number of a Java source file and want to get the sourounding method for that line number programatically.
I looked into ANTLR which didn't help me much.
Janino (http://www.janino.net) seems promising, I would scan and parse (and if necessary compile) the code. Then I could use JDI and
ReferenceType.locationsOfLine(int lineNumber)
Still I don't know how to use JDI for doing this and didn't find a tutorial that goes anywhere in this direction.
Maybe there is some other way that I am completely missing.
You can use ASM's CodeVisitor to retrieve the debugging line information from a compiled class. This saves you the parsing of Java source files.
For class A:
This produces:
If you need this information at runtime. You can create an exception and have a look at the stack trace elements.
If you're using Java 6, and if you don't mind using Sun's APIs, then you can use the javac API. You'll need to add
tools.jar
to your classpath.maybe you can throw an Exception, catch it, extract the corresponding stacktrace element to get the method name.