Monday, March 24, 2008

Extracting Class Info with Java Reflection

Here is some code that I use to extract information about classes using Java Reflection. It takes the class name as a String argument (i.e. "java.util.Date"), then outputs the information to standard output.

It works best when incorporated into a loop reading class names from an input file or some other data source. For you Intralink Scripting users out there, the data will appear in your .proi.log file.


public void getClassData ( String className ) throws Exception {

System.out.println( "Class: " + className );
System.out.println();

try {

Class c = Class.forName(className);

System.out.println( " package: " + c.getPackage().getName() );
System.out.println( " isinterface: " + c.isInterface() );

System.out.print( " superclass: " );
if (c.getSuperclass() == null) { System.out.println(); }
Class sc = c;
int indent = 0;
while (sc.getSuperclass() != null) {
if (indent > 0) {
for (int i=0; i<indent; i++) { System.out.print( " " ); }
System.out.print( " -> " );
}
System.out.println( sc.getSuperclass().getName() );
sc = sc.getSuperclass();
indent += 3;
}

System.out.println();


System.out.println("Constructors: ");
try {
// Constructor[] cons = c.getDeclaredConstructors();
Constructor[] cons = c.getConstructors();
for (int i = 0; i < cons.length; i++) {
// System.out.println( " constr: " + cons[i].toString() );
System.out.println( " " + cons[i].toString() );
}
}
catch (Exception e1) {
// cannot get constructor info
}
System.out.println();


System.out.println("Interfaces: ");
try {
Class intfs[] = c.getInterfaces();
for (int i = 0; i < intfs.length; i++) {
// System.out.println( " intf: " + intfs[i].toString() );
System.out.println( " " + intfs[i].toString() );
}
}
catch (Exception e1) {
// cannot get interface info
}
System.out.println();


System.out.println("Methods: ");
try {
// Method meths[] = c.getDeclaredMethods();
Method meths[] = c.getMethods();
for (int i = 0; i < meths.length; i++) {
// System.out.println( " method " + meths[i].getName() + "(): " + meths[i].toString() );
System.out.println( " " + meths[i].getName() + "(): " + meths[i].toString() );
}
}
catch (Exception e1) {
// cannot get method info
}
System.out.println();


System.out.println("Fields: ");
try {
// Field flds[] = c.getDeclaredFields();
Field flds[] = c.getFields();
for (int i = 0; i < flds.length; i++) {
// System.out.println( " field " + flds[i].getName() + ": " + flds[i].toString() );
System.out.println( " " + flds[i].getName() + ": " + flds[i].toString() );
}
}
catch (Exception e1) {
// cannot get method info
}
System.out.println();


}
catch (Exception e) {
System.out.println( " Problem getting class information!" );
System.out.println( e.getMessage() );
System.out.println();
}


System.out.println();
System.out.flush();

}

This is easily modified to output data to a named file. Let me know if you need to see that.

No comments: