Posted By

peceps on 10/15/10


Tagged

get Reflection getter getters


Versions (?)

Get value from object using getter via reflection


 / Published in: Java
 

  1. /**
  2.   * Gets value from object using reflection.
  3.   *
  4.   * @param object the object
  5.   * @param fieldName the field
  6.   * @return the value
  7.   */
  8. protected String getValueFromObject(Object object, String fieldName) {
  9.  
  10. // get class
  11. Class clazz = object != null ? object.getClass() : null;
  12. if (clazz == null) {
  13. return null;
  14. }
  15.  
  16. // get object value using reflection
  17. String getterName = "get" + fieldName;
  18. try {
  19. @SuppressWarnings("unchecked")
  20. Method method = clazz.getMethod(getterName);
  21. Object valueObject = method.invoke(object, (Object[]) null);
  22. return valueObject != null ? valueObject.toString() : "";
  23. } catch (Exception e) {
  24. // ignore all reflection errors
  25. }
  26.  
  27. return null;
  28. }

Report this snippet  

You need to login to post a comment.