2 Ocak 2011 Pazar

printing an object with reflection api (for debug purpose)

I am at work on a very very cold sunday morning.. then lets learn something in companionship of a cup of hot coffee in this empty office..
my aim is to print an objects attributes regardless of its type.. in other words, i do not want to write seperate debug statements for all my object types.. i want a static method written in java reflection api and use it everywhere.. by the way, i am only interested in printing methods that start with get...()..

good code samples here: http://java.sun.com/developer/technicalArticles/ALT/Reflection/

here is the code to do that:
public static void printObject(String className, Object classItself) {
try {
System.out.println("PRINTING-OBJ " + className);
Class c = Class.forName(className);
Field[] f = c.getFields();
for (int i = 0; i <>
System.out.println(f[i]);
}
Method[] m = c.getDeclaredMethods();
for (int i = 0; i <>
// System.out.println(m[i].getName());
if (m[i].getName().startsWith("get")) {
try {
System.out.println("METHOD: " + m[i].getName() + " : " + m[i].invoke(classItself, null));
} catch (Exception ex) {
// do nothing
}
}
}
System.out.println("END OF PRINTING-OBJ " + className);
} catch (Exception ex) {
// do nothing
}
}
a sample call:

Helper.printObject(Parameter.class.getCanonicalName(), parameter);

output:

PRINTING-OBJ .admin.Parameter
METHOD: getName : name
METHOD: getDescription : description
METHOD: getCode : -10117439
END OF PRINTING-OBJ admin.Parameter

Hiç yorum yok:

Yorum Gönder