THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

The reflection-based code has semantically equivalent safety checks, although the checks that are made by the
compiler for direct invocation can be made only at run time when you use invoke. The access checking may
be done in a somewhat different wayyou might be denied access to a method in your package by the security
manager, even if you could invoke that method directly.


These are good reasons to avoid using this kind of invocation when you can. It's reasonable to use invokeor
the getset methods of Fieldwhen you are writing a debugger or other generic applications that require
interpreting user input as manipulations of objects. A Method object can be used somewhat like a method
pointer in other languages, but there are better toolsnotably interfaces, abstract classes, and nested classesto
address the problems typically solved by method pointers in those languages.


Exercise 16.7: Modify your Interpret program to invoke methods on the object. You should properly
display any values returned or exceptions thrown.


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 the returned object is of type T.


Creating a new object in this way is useful when you want to write general code and let the user specify the
class. For example, you could modify the general sorting algorithm tester from "Designing a Class to Be
Extended" 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
}
}


This is almost exactly like TestSort.main (see page 112), but we have removed all type names. This
main method can be used to test any subclass of SortDouble that provides a no-arg constructor. You don't
have to write a main for each type of sorting algorithmthis generic main works for them all. All you need to
do is execute


java TestSort TestClass ...

Free download pdf