Java: print values of all get-methods of an object

/ Published in: Java
Save to your folder(s)

Surprisingly often I want to print all the values of some object for debugging reasons, and if the object has a lot of different get methods (and toString is not good for this), it is a pain to write all the print commands. That's when this snippet is useful (yes, it is not perfect, and if get methods are not named as "getXXX", it does not find those, but it is your own fault then).

Copy this code and paste it in your HTML
  1. for (java.lang.reflect.Method m : object.getClass().getMethods()) {
  2. try {
  3. if (m.getName().startsWith("get")
  4. && m.getReturnType() != void.class
  5. && m.getParameterTypes().length == 0) {
  6. System.out.println(m.getName().replace("get", "") + ": " + m.invoke(object));
  7. }
  8. } catch (Exception e) {
  9. e.printStackTrace();
  10. }
  11. }

Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.