How to access the private variables of a class in its subclass?

前端 未结 28 2200
清歌不尽
清歌不尽 2020-12-17 09:46

This is a question I was asked in an interview: I have class A with private members and Class B extends A. I know private members of a class cannot be accessed, but the qu

相关标签:
28条回答
  • 2020-12-17 10:41

    To access private variables of parent class in subclass you can use protected or add getters and setters to private variables in parent class..

    0 讨论(0)
  • 2020-12-17 10:42

    Reflection? Omitting imports, this should work:

    public class A {
    
        private int ii = 23;
    
    }
    
    public class B extends A {
    
        private void readPrivateSuperClassField() throws Exception {
            Class<?> clazz = getClass().getSuperclass();
            Field field = clazz.getDeclaredField("ii");
            field.setAccessible(true);
            System.out.println(field.getInt(this));
        }
    
        public static void main(String[] args) throws Exception {
            new B().readPrivateSuperClassField();
        }
    
    }
    

    It'll not work if you do something like that before the of invocation readPrivateSuperClassField();:

    System.setSecurityManager(new SecurityManager() {
            @Override
            public void checkMemberAccess(Class<?> clazz, int which) {
                if (clazz.equals(A.class)) {
                    throw new SecurityException();
                } else {
                    super.checkMemberAccess(clazz, which);    
                }
            }
        });
    

    And there are other conditions under which the Reflection approach won't work. See the API docs for SecurityManager and AccessibleObject for more info. Thanks to CPerkins for pointing that out.

    I hope they were just testing your knowledge, not looking for a real application of this stuff ;-) Although I think an ugly hack like this above can be legit in certain edge cases.

    0 讨论(0)
  • 2020-12-17 10:43

    The architecture is broken. Private members are private because you do not want them accessed outside the class and friends.

    You can use friend hacks, accessors, promote the member, or #define private public (heh). But these are all short term solutions - you will probably have to revisit the broken architecture at some stage.

    0 讨论(0)
  • 2020-12-17 10:45

    By using public accessors (getters & setters) of A's privates members ...

    0 讨论(0)
提交回复
热议问题