Frage

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?

War es hilfreich?

Lösung

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top