SyntaxHighlighter

Friday, July 5, 2013

Java Reflection and the Class Hierarchy - retrieving Fields

Java Reflection and the Class Hierarchy - retrieving Fields


here's a little snippet to keep in mind when trying to identify a field in a possible n tier class hierarchy;

  Class < ? > cls = object.getClass();
  while (true) {
   try {
    field = cls.getDeclaredField(someField);
    break;
   }
   catch (NoSuchFieldException e) {
    cls = cls.getSuperclass();
   }
   catch (Exception e) {
    throw new RuntimeException(e);
   }
  }
  
  field.setAccessible(true); 

.

1 comment:

  1. http://www.scribd.com/doc/163398138/Java-Reflection-with-Generics-Practical-Case

    ReplyDelete