Tipsi :
I need to use a method from a class that I obtained via the Class.forName() method. I'll give you an example:
public class Greeter {
public String getGreeting() {
return "Hello World!";
}
}
Now I want to dynamically obtain this class using a string and use it's method like so:
Class c = Class.forName("Greeter");
System.out.println(c.getGreeting());
Now this obviously didn't work, because Java doesn't recognize the class as a Greeter class yet. How would I go about doing this without having to hard-code the fact that it's a Greeter class?
Elliott Frisch :
Not directly, you would need an instance of the Class
in order to invoke the method. For example,
Class<?> cls = Class.forName("Greeter");
try {
Object o = cls.getConstructor(null).newInstance(null);
System.out.println(((Greeter) o).getGreeting());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You mention in the comments that you don't "know" it's a Greeter
. You should program to a common interface, but failing that; it's possible to get the method by name as well. For example,
Object o = cls.getConstructor(null).newInstance(null);
Method m = cls.getMethod("getGreeting", null);
System.out.println(m.invoke(o, null));
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=324968&siteId=1