Java Reference
In-Depth Information
static void indent(int numSpaces)
{
for (int i = 0; i < numSpaces; i++)
System.out.print(' ');
}
}
Listing4-10
presentsthesourcecodetoadecompilertoolthatusesreflectiontoob-
taininformationaboutthistool'ssolitarycommand-lineargument,whichmustbeaJava
referencetype(suchasaclass).Thedecompilerletsyououtputthetypeandnamein-
formation for a class's fields, constructors, methods, and nested types; it also lets you
output the members of interfaces, enums, and annotation types.
Afterverifyingthatonecommand-lineargumenthasbeenpassedtothisapplication,
main()
calls
forName()
to try to return a
Class
object representing the class or
interface identified by this argument. If successful, the returned object's reference is
passed to
decompileClass()
, which decompiles the type.
forName()
throws an instance of the checked
ClassNotFoundException
class when it cannot locate the class's classfile (perhaps the classfile was erased prior
toexecutingtheapplication).Italsothrows
LinkageError
whenaclass'sclassfileis
malformed,and
ExceptionInInitializerError
whenaclass'sstaticinitializa-
tion fails.
Note
ExceptionInInitializerError
isoftenthrownastheresultofaclass
initializer throwing an unchecked exception. For example, the class initializer in the
following
FailedInitialization
class results in
ExceptionInInitial-
izerError
because
someMethod()
throws
NullPointerException
:
class FailedInitialization
{
static
{
someMethod(null);
}
static void someMethod(String s)
{
int len = s.length(); // s contains null
System.out.println(s+"'s length is "+len+" charac-
ters");