Java Reference
In-Depth Information
Listing 3-9. Creating an Object Using newInstance( ) Method of a Class Object
// NewInstanceTest.java
package com.jdojo.reflection;
public class NewInstanceTest {
public static void main(String[] args) throws InstantiationException {
Class<Person> personClass = Person.class;
try {
// Create new instance of Person class
Person p = personClass.newInstance();
System.out.println(p);
}
catch (InstantiationException | IllegalAccessException e) {
System.out.println(e.getMessage());
}
}
}
Person: id=-1, name=Unknown
Note that there are two exceptions listed in the catch block in the main() method. The InstantiationException
is thrown if there was any problem in creating the object, for example, attempting to create an object of an abstract
class, an interface type, primitive types, or the void type. This exception may also be thrown if the class does not have
a no-args constructor. The IllegalAccessException may be thrown if the class itself is not accessible or the no-args
constructor is not accessible. For example, if there is a no-args constructor and it is declared private. In this case, this
exception will be thrown.
You can create an object using reflection by invoking a constructor of your choice. In this case, you must get the
reference to the constructor you want to invoke and invoke the newInstance() method on that constructor reference.
The Person class has a constructor with a signature Person(int id, String name) . You can get the reference of this
constructor as shown:
Constructor<Person> cons = personClass.getConstructor(int.class, String.class);
After you get the reference to the desired constructor, you need to call the newInstance() method on that
constructor passing the arguments to the constructor to create an object.
Listing 3-10 illustrates how to use a constructor of your choice to create an object using reflection. The catch
block lists a generic exception to catch all exceptions for brevity. Note that the Constructor<T> class is a generic type.
Its type parameter is the class type that declares the constructor, for example, Constructor<Person> type represents a
constructor for the Person class.
Listing 3-10. Using a Specific Constructor to Create a New Object
// InvokeConstructorTest.java
package com.jdojo.reflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class InvokeConstructorTest {
public static void main(String[] args) {
Class<Person> personClass = Person.class;
 
Search WWH ::




Custom Search