THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

everything ultimately extends it. Use the reference for the Class object for the Object type.


Exercise 16.2: Modify TypeDesc to show whether the named type is a nested type, and if so, what other
type it is nested within.


16.1.3. Examining Class Members


The Class class contains a set of methods you can use to examine the class's components: its fields,
methods, constructors, and nested types. Special types are defined to represent each of these, which you will
learn about in detail in later sections: Field objects for fields, Method objects for methods,
Constructor objects for constructors, and for nested types, the Class objects you have already seen.


These methods come in four variants depending on whether you want all members or a particular member,
only public members or any members, only members declared in the current class or inherited members as
well.


You can request all the public members of a specific kind that are either declared in the class (interface) or
inherited, by using one of the following:[2]


[2] A number of methods return arrays of raw types, such as Class[] or Constructor[].
These methods should have been generified to return wildcard types: Class<?>[] or
Constructor<?>[].

public Constructor[] getConstructors()
public Field[] getFields()
public Method[] getMethods()
public Class[] getClasses()


Because constructors are not inherited, getConstructors returns Constructor objects only for public
constructors declared in the current class.


You can also ask for the members of a specific kind that are actually declared in the class (interface), as
opposed to being inherited. Such members need not be public:


public Constructor[] getDeclaredConstructors()
public Field[] getDeclaredFields()
public Method[] getDeclaredMethods()
public Class[] getDeclaredClasses()


In each case, if there is no member of that kind, you will get an empty array. The getClasses and
getdeclaredClasses methods return both nested classes and nested interfaces.


Requesting a particular member requires you to supply further information. For nested types this is simply the
name of the nested type and, in fact, there are no special methods to do this because Class.forName can
be used for this purpose. Particular fields are requested using their name:


public Field getField(String name)
public Field getDeclaredField(String name)

Free download pdf