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.ParameterMETHOD: getName : nameMETHOD: getDescription : descriptionMETHOD: getCode : -10117439END OF PRINTING-OBJ admin.Parameter
Hiç yorum yok:
Yorum Gönder