Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

Chapter 16: Exploring java.lang 417


The methods defined byClassare often useful in situations where run-time type
informationabout an object is required. As Table 16-15 shows, methods are provided that
allow you to determine additional information about a particular class, such as its public
constructors, fields, and methods. Among other things, this is important for the Java Beans
functionality, which is discussed later in this book.
The following program demonstratesgetClass( )(inherited fromObject) and
getSuperclass( )(fromClass):


// Demonstrate Run-Time Type Information.


class X {
int a;
float b;
}


class Y extends X {
double c;
}


class RTTI {


Method Description
Method getMethod(StringmethName,
Class<?> ...paramTypes)
throws NoSuchMethodException,
SecurityException

Returns aMethodobject that represents the
method specified bymethNameand having the
parameter types specified byparamTypes.

Method[ ] getMethods( )
throws SecurityException

Obtains aMethodobject for each public method
of the invoking object and stores them in an array.
Returns a reference to this array.
String getName( ) Returns the complete name of the class or
inter face of the invoking object.
ProtectionDomain getProtectionDomain( ) Returns the protection domain associated with the
invoking object.
Class<? super T> getSuperclass( ) Returns the superclass of the invoking object. The
return value isnullif the invoking object is of type
Object.
boolean isInter face( ) Returnstrueif the invoking object is an inter face.
Other wise, it returnsfalse.
T newInstance( )
throws IllegalAccessException,
InstantiationException

Creates a new instance (i.e., a new object) that is
of the same type as the invoking object. This is
equivalent to usingnewwith the class’ default
constructor. The new object is returned.
String toString( ) Returns the string representation of the invoking
object or inter face.

TABLE 16-15 A Sampling of Methods Defined byClass(continued)

Free download pdf