Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With Java reflection how to instantiate a new object, then call a method on it?

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?

like image 876
Vinzz Avatar asked Nov 23 '09 11:11

Vinzz


People also ask

How do you instantiate an object using a reflection?

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.

How do we instantiate an object in Java?

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.

What method is called to instantiate an object?

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.

How do you call a method in Java?

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).


1 Answers

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

like image 146
Bozho Avatar answered Sep 20 '22 02:09

Bozho