Muhammad Asaduzzaman
Muhammad Asaduzzaman

Reputation: 1241

How to programmatically extract method body from a class in Java Source Code?

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.

Upvotes: 1

Views: 2713

Answers (3)

Eric
Eric

Reputation: 1

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

Upvotes: -1

Devon_C_Miller
Devon_C_Miller

Reputation: 16528

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.

Upvotes: 3

Andrew Hare
Andrew Hare

Reputation: 351516

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.

Upvotes: -1

Related Questions