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?
We can use newInstance() method on the constructor object to instantiate a new instance of the class. Since we use reflection when we don't have the classes information at compile time, we can assign it to Object and then further use reflection to access it's fields and invoke it's methods.
Java provides the new keyword to instantiate a class. We can also instantiate the above class as follows if we defining a reference variable. We observe that when we use the new keyword followed by the class name, it creates an instance or object of that class.
Instantiating an Object new requires a single argument: a call to a constructor method. Constructor methods are special methods provided by each Java class that are responsible for initializing new objects of that type. The new operator creates the object, the constructor initializes it.
To call a method in Java, write the method name followed by a set of parentheses (), followed by a semicolon ( ; ). A class must have a matching filename ( Main and Main. java).
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.
See the java.lang.Class docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With