Java Reference
In-Depth Information
// Get the name of the constructor
String constructorName = constructor.getName();
// Get the parameters of the constructor
ArrayList<String> paramsList =
ExecutableUtil.getParameters(constructor);
String params = ExecutableUtil.arrayListToString(paramsList, ",");
// Get the Exceptions thrown by the constructor
String throwsClause = ExecutableUtil.getThrowsClause(constructor);
constructorList.add(modifiers + " " + constructorName
+ "(" + params + ") " + throwsClause);
}
return constructorList;
}
}
Constructors for com.jdojo.reflection.Person
public com.jdojo.reflection.Person()
public com.jdojo.reflection.Person(int arg0,String arg1)
Creating Objects
Java lets you use reflection to create objects of a class. The class name needed not be known until runtime. You can
create the object by invoking one of the constructors of the class. You can also access the values of fields of objects, set
their values, and invoke their methods. The following sections explain these features in detail. There are two ways to
create objects:
•
Using the no-args constructor of the class
•
Using any constructor of the class
If you have the reference of a
Class
object, you can create an object of the class using the
newInstance()
method on the
Class
class. This method takes no parameter. It is equivalent to using the
new
operator on the no-args
constructor of the class. If
personClass
is the reference to the class object of the
Person
class, you can create a
Person
object as shown:
Person p = personClass.newInstance();
Note that 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();
Listing 3-9 illustrates how to use the
newInstance()
method of the
Class
object to create an object of the
Person
class.