Java Reference
In-Depth Information
Example 8−1: ShowClass.java (continued)
for(int i = 0; i < constructors.length; i++) // Display constructors.
print_method_or_constructor(constructors[i]);
System.out.println(" // Fields");
Field[] fields = c.getDeclaredFields();
// Look up fields.
for(int i = 0; i < fields.length; i++)
// Display them.
print_field(fields[i]);
System.out.println(" // Methods");
Method[] methods = c.getDeclaredMethods();
// Look up methods.
for(int i = 0; i < methods.length; i++)
// Display them.
print_method_or_constructor(methods[i]);
System.out.println("}");
// End class member listing.
}
/** Return the name of an interface or primitive type, handling arrays. */
public static String typename(Class t) {
String brackets = "";
while(t.isArray()) {
brackets += "[]";
t = t.getComponentType();
}
String name = t.getName();
int pos = name.lastIndexOf('.');
if (pos != -1) name = name.substring(pos+1);
return name + brackets;
}
/** Return a string version of modifiers, handling spaces nicely. */
public static String modifiers(int m) {
if (m == 0) return "";
else return Modifier.toString(m) + " ";
}
/** Print the modifiers, type, and name of a field */
public static void print_field(Field f) {
System.out.println(" " + modifiers(f.getModifiers()) +
typename(f.getType()) + " " + f.getName() + ";");
}
/**
* Print the modifiers, return type, name, parameter types and exception
* type of a method or constructor. Note the use of the Member interface
* to allow this method to work with both Method and Constructor objects
**/
public static void print_method_or_constructor(Member member) {
Class returntype=null, parameters[], exceptions[];
if (member instanceof Method) {
Method m = (Method) member;
returntype = m.getReturnType();
parameters = m.getParameterTypes();
exceptions = m.getExceptionTypes();
System.out.print(" " + modifiers(member.getModifiers()) +
typename(returntype) + " " + member.getName() +
"(");
} else {
Constructor c = (Constructor) member;
Search WWH ::




Custom Search