Java Reference
In-Depth Information
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 sub-
class 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 ...
for any sorting class (such as SimpleSortDouble ) and it will be loaded and
run.
Note that whereas newInstance returns a T , Class.forName returns a
Class<?> . This means that the actual kind of object returned by newIn-
stance is unknown, so the cast is needed. You could instead get a class
object of the exact type needed using asSubclass , and invoke newInstance
without needing a cast:
Class<? extends SortDouble> classFor =
Class.forName(name).asSubclass(SortDouble.class);
SortDouble sorter = classFor.newInstance();
In either case, if the named class is not a subtype of SortDouble , then a
ClassCastException will be thrown.
The newInstance method can throw a number of different exceptions if
used inappropriately. If the class doesn't have a no-arg constructor, is
an abstract class, or interface, or if the creation fails for some other
reason, you will get an InstantiationException . If the class or the no-arg
constructor is not accessible an IllegalAccessException is thrown. If the
current security policy disallows the creation of a new object a Secur-
ityException is thrown. Finally, creating a new object may require the
class to be initialized so it is also possible for an ExceptionInInitializer-
Error to be thrown.
 
Search WWH ::




Custom Search