Java Reference
In-Depth Information
try {
// Get the constructor "Person(int, String)"
Constructor<Person> cons =
personClass.getConstructor(int.class, String.class);
// Invoke the constructor with values for id and name
Person chris = cons.newInstance(1994, "Chris");
System.out.println(chris);
}
catch (NoSuchMethodException | SecurityException |
InstantiationException | IllegalAccessException |
IllegalArgumentException | InvocationTargetException e) {
System.out.println(e.getMessage());
}
}
}
Person: id=1994, name=Chris
Invoking Methods
You can invoke methods of an object using reflection. You need to get the reference to the method that you want
to invoke. Suppose you want to invoke the setName() method of the Person class. You can get the reference to the
setName() method as
Class<Person> personClass = Person.class;
Method setName = personClass.getMethod("setName", String.class);
To invoke this method, call the invoke() method on the method's reference. The first parameter of the invoke()
method is the object on which you want to invoke the method and the second parameter is a varargs arguments
parameter in which you pass all the argument values in the same order as declared in the method's declaration. Since
the setName() method takes a String argument, you need to pass a String object as the second argument to the
invoke() method.
The same invoke() method is used to invoke static methods as well. In case of a static method, the first argument
is ignored; you may specify null for the first argument.
Listing 3-11 illustrates how to invoke a method using reflection.
Listing 3-11. Invoking a Method on an Object Reference Using Reflection
// InvokeMethodTest.java
package com.jdojo.reflection;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class InvokeMethodTest {
public static void main(String[] args) {
Class<Person> personClass = Person.class;
try {
// Create an object of Person class
Person p = personClass.newInstance();
 
Search WWH ::




Custom Search