Question

I'm asking for if there is a way where I could obtain a string (ie "Foo.bar();" ), and search my jvm for the class Foo and call the static method bar? If so, may you share it?

Was it helpful?

Solution

Here it is using Java reflection:

try {
    Class<?> myClass = Class.forName("Foo");
    Method myMethod = myClass.getMethod("bar");
    Object retObject = myMethod.invoke(null);
} catch (Exception e) {
    // handle errors here...
    e.printStackTrace();
}

This is if bar() is a static method here, and if it has no parameter.

See this tutorial for more information on reflection.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top