THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

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 newInstance 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 SecurityException is thrown. Finally, creating a new object may require the class to
be initialized so it is also possible for an ExceptionInInitializerError to be thrown.


The newInstance method of Class invokes only a no-arg constructor. If you want to invoke any other
constructor then you must use the Class object to get the relevant Constructor object and invoke
newInstance on that Constructor, passing the appropriate parameters.


The Constructor class, together with its inherited Member methods allows you to obtain complete
information about the declaration of a constructor and allows you to invoke the constructor to obtain a new
instance of that class.


public Type[]getGenericParameterTypes()

Returns an array of Type objects for each of the parameter types accepted by
this constructor, in the order in which the parameters are declared. If the
constructor has no parameters an empty array is returned.

public Type[]getGenericExceptionTypes()

Returns an array of Type objects for each of the exception types listed in the
throws clause for this constructor, in the order they are declared. If there
are no declared exceptions an empty array is returned.

As with Method objects, the above are mirrored by the legacy versions getParameterTypes and
getExceptionTypes, respectively.


The Constructor class is similar to Method, implementing the same interfaces (AnnotatedElement
and GenericDeclaration) and defining similar methods (getParameterAnnotations and
isVarArgs).


To create a new instance of a class from a Constructor object, you invoke its newInstance method.


public TnewInstance(Object... args)throws
InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException
Free download pdf