I have a poorly designed class in a 3rd-party JAR
and I need to access one of its private fields. For example,
why should I need to choose priv
You need to do the following:
private static Field getField(Class> cls, String fieldName) {
for (Class> c = cls; c != null; c = c.getSuperclass()) {
try {
final Field field = c.getDeclaredField(fieldName);
field.setAccessible(true);
return field;
} catch (final NoSuchFieldException e) {
// Try parent
} catch (Exception e) {
throw new IllegalArgumentException(
"Cannot access field " + cls.getName() + "." + fieldName, e);
}
}
throw new IllegalArgumentException(
"Cannot find field " + cls.getName() + "." + fieldName);
}