How to read the value of a private field from a different class in Java?

前端 未结 14 1625
梦毁少年i
梦毁少年i 2020-11-21 11:28

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

14条回答
  •  有刺的猬
    2020-11-21 12:05

    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);
    }
    

提交回复
热议问题