THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

private static void printMembers(Member[] mems) {
for (Member m : mems) {
if (m.getDeclaringClass() == Object.class)
continue;
String decl = m.toString();
System.out.print(" ");
System.out.println(strip(decl, "java.lang."));
}
}


// ... definition of strip ...
}


We first get the Class object for the named class. We then get and print the arrays of member objects that
represent all the public fields, constructors, and methods of the class. The printMembers method uses the
Member object's toString method to get a string that describes the member, skipping members that are
inherited from Object (using getDeclaringClass to see which class the member belongs to) since these are
present in all classes and so are not very useful to repeat each time (strip removes any leading
"java.lang." from the name). Here is the output when the program is run on the Attr class from page
76:


class Attr
public Attr(String)
public Attr(String, Object)
public String Attr.toString()
public String Attr.getName()
public Object Attr.getValue()
public Object Attr.setValue(Object)


Exercise 16.3: Modify ClassContents to show information for all declared and all public inherited
members. Make sure you don't list anything twice.


16.1.4. Naming Classes


The Class objects in the TypeDesc program are obtained using the static method Class.forName,
which takes a string argument and returns a Class object for the type with that name. The name must be the
binary name of a class or interface, or else be a specially named array typethese are defined below.


Every type is represented by a number of different names. The actual class or interface name is the simple
name of the type. This is the shortest name you could write in your program to represent a given type. For
example, the simple name of java.lang.Object is Object, the simple name of the nested EnTRy
interface in the java.util.Map interface is EnTRy, the simple name of the type representing an array of
Object instances is Object[], and the simple name of an array of int is int[]. All types except for
anonymous inner classes have simple names. You can get the simple name of a type from the Class method
getSimpleName.


The canonical name of a type is its full name, as you would write it in your programs, including, if applicable,
the package and enclosing type in which the type was declared. For example, the canonical name of Object
is java.lang.Object; for the nested EnTRy interface it is java.util.Map.Entry; for an array of
Object instances it is java.lang.Object[]; and for an array of int is int[]. In more specific terms,
the canonical name of a top-level class or interface is its package name followed by dot, followed by its
simple name. The canonical name of a nested type is the canonical name of the type in which it is declared,
followed by dot, followed by its simple name. The canonical name of an array type is the canonical name of

Free download pdf