views:

121

answers:

3

Hi, I want to extract method body from a Java Source Code. Suppose I have the following code:

public class A{

  public void print(){
    System.out.println("Print This thing");
    System.out.println("Print This thing");
    System.out.println("Print This thing");
  }

}

My objective is not to extract the method name (in this case print) but also the bode of the method(In this case the three print statement inside the print method). Can anyone suggest how can I do so? Is their any library available for doing so.

A: 

Here is a hack-ish way I have seen the method name retrieved:

String methodName = new Exception()
                           .getStackTrace()[0]
                           .getMethodName();

Someone with stronger Java-fu might be able to give a cleaner approach and also provide a way to retrieve the body of the method.

Andrew Hare
nice clever solution, but it won't show the body of the method too... only the name.
oedo
A: 

Alt-Shift-I in eclipse will attempt to inline the method call (with your cursor on the method call).

Eric
+2  A: 

If you're talking about manipulating source code, all of the IDEs have some degree of refactoring support that will allow you to select one or more lines of code and create a method consisting of those lines.

If you want to do that programatically, you'll need to parse the source file. You could write a lexer and parser, but that's a lot of work unless you're building an IDE. You may want to take a look at Annotation processing. That probably won't go far enough unless you also use a Compiler Tree API. Note, however that when you go there you're venturing off the "run anywhere" path and entering "implementation specific" land.

If you're looking to manipulate things at runtime, then take a look at BCEL or ASM and Java Agents.

Devon_C_Miller
Thx for the suggestion. I do not want to manipulate things at runtime. The input will be plain java source code. I found the eclipse JDT offer source code manipulation. I will try that. Is there any other such open source library?
Muhammad Asaduzzaman
There are several (google for java refactoring tool). RefactorIt (http://refactorit.sourceforge.net/) is probably the best maintained. It's also available as a plugin for NetBeans and Eclipse.
Devon_C_Miller