1

For example, If I have a Example.java file which as shown below

Class Example{
int a;
int b;
void helloworld(){
System.out.println("HelloWorld");
}
void hello(){
System.out.println("HelloWorld");
}

How can I get the contents of function helloWorld() as a string programmatically, like

void helloworld(){
System.out.println("HelloWorld");
}

I mean it should accept method name as input and return contents of it as string??

Cœur
  • 37,241
  • 25
  • 195
  • 267
shashank
  • 65
  • 6
  • 1
    You can't (in any meaningful way). At runtime you're working with bytecode, so it doesn't even make sense to try to get the source code contents of a specific method. – Kayaman Oct 25 '19 at 09:46
  • Oh ok. Then Is there any way to do it correctly using file manipulation functions?? – shashank Oct 25 '19 at 09:53
  • What function modifiers are possible there? – Gaurav Jeswani Oct 25 '19 at 09:54
  • I mean we can get contents of whole java file as a string, but getting contents of a particular function would be difficult,i guess. – shashank Oct 25 '19 at 09:56
  • @SHASHANKHA well you could read the source code, and parse the method's code from there, but why do you want to do that? – Kayaman Oct 25 '19 at 10:02
  • You can do that, but that won't be full flash. This will depend on the basis of formatting of code. You will miss method modifier. Otherwise main content of method you can get. – Gaurav Jeswani Oct 25 '19 at 10:04
  • You can do that using regex and capture the () symbols to get method name – Erwin Oct 25 '19 at 10:15

1 Answers1

0

it's not possible to get method body as it is bytecode. This question was asked long before and you can find the response at How do I print the method body reflectively?

Maximum you can get is the method signature as shown in below example.

import java.lang.reflect.Method;

public class reflectionexample {

    public static void main(String[] args) {

        try {
            Class c = TestMe.class;
            Object t = c.newInstance();
            Method[] allMethods = c.getDeclaredMethods();
            for (Method method : allMethods) {
                System.out.println(method.toGenericString());
            }

        } catch (Exception e) {
            e.printStackTrace();
        } 
    }
}


class TestMe {

    void extractMePlease(String justLikeThat) {
        System.out.println("is it working?");
    }
}

OUTPUT

void compareInt.TestMe.extractMePlease(java.lang.String)

Hope it helps!

www.hybriscx.com
  • 1,129
  • 4
  • 22