Java can use reflection to create objects of a class.
You can create the object by invoking one of the constructors of the class.
You can access the values of fields of objects, set their values, and invoke their methods.
There are two ways to create objects:
You can create an object of the class using the newInstance() method on the Class class.
It is equivalent to using the new operator on the no-args constructor of the class. For example,
Person p = personClass.newInstance();
The return type of the newInstance() method is the same as the type parameter T of the Class<T> class.
The above statement has the same effect as the following statement:
Person p = new Person();
The following code illustrates how to use the newInstance() method of the Class object to create an object of the String class.
public class Main { public static void main(String[] args) throws InstantiationException { Class<String> c = String.class; try {/*w w w .ja v a 2 s . co m*/ // Create new instance of Person class String p = c.newInstance(); System.out.println(p); } catch (InstantiationException | IllegalAccessException e) { System.out.println(e.getMessage()); } } }
There are two exceptions listed in the catch block in the main() method.
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.
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 private no-args constructor.