Java Reference
In-Depth Information
16.8. Creating New Objects and the Constructor Class
You can use a Class object's newInstance method to create a new instance
(object) of the type it represents. This method invokes the class's no-arg
constructor and returns a reference to the newly created object. For a
class object of type Class<T> the returned object is of type T .
Creating a new object in this way is useful when you want to write gener-
al code and let the user specify the class. For example, you could modify
the general sorting algorithm tester from " Designing a Class to Be Ex-
tended " on page 108 so that the user could type the name of the class
to be tested and use that as a parameter to the forName lookup method.
Assuming that the given class name was valid, newInstance could then be
invoked to create an object of that type. Here is a new main method for a
general TestSort class:
static double[] testData = { 0.3, 1.3e-2, 7.9, 3.17 };
public static void main(String[] args) {
try {
for (String name : args) {
Class<?> classFor = Class.forName(name);
SortDouble sorter
= (SortDouble) classFor.newInstance();
SortMetrics metrics
= sorter.sort(testData);
System.out.println(name + ": " + metrics);
for (double data : testData)
System.out.println("\t" + data);
}
} catch (Exception e) {
System.err.println(e); // report the error
}
}
 
Search WWH ::




Custom Search