I'm pretty new to Java, and I'm facing a reflection issue.
Let's say i have to dynamically call the method fooMethod on an instance of the class Foobar
I got so far an instance of Foobar with:
Object instance = Class.forName("Foobar").newInstance();
Let's say I know there's a method fooMethod on this object (I can even check this with Class.forName("Foobar").getDeclaredMethods() ) , how to call it, please?
解决方案
Method method = getClass().getDeclaredMethod("methodName");
m.invoke(obj);
This is in case the method doesn't have arguments. If it has, append the argument types as arguments to this method.
obj is the object you are calling the method on.