Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a method named "string" at runtime in Java and C

How can we call a method which name is string at runtime. Can anyone show me how to do that in Java and C.

like image 876
dbtek Avatar asked May 21 '10 14:05

dbtek


1 Answers

In java it can be done through the reflection api.

Have a look at Class.getMethod(String methodName, Class... parameterTypes).

A complete example (of a non-static method with an argument) would be:

import java.lang.reflect.*;
public class Test {

    public String methodName(int i) {
        return "Hello World: " + i;
    }

    public static void main(String... args) throws Exception {
        Test t = new Test();
        Method m = Test.class.getMethod("methodName", int.class);
        String returnVal = (String) m.invoke(t, 5);
        System.out.println(returnVal);
    }
}

Which outputs:

Hello World: 5

like image 197
aioobe Avatar answered Nov 15 '22 02:11

aioobe