Can I override a private method in Java?

前端 未结 10 1211
天涯浪人
天涯浪人 2020-11-29 08:26

I know I can use reflection to invoke a private method, and to get or set the value of a private variable, but I want to override a method.

public class Supe         


        
10条回答
  •  眼角桃花
    2020-11-29 09:28

    Private methods are not inherited and cannot be overridden in any way. Whoever told you you can do it with reflection was either lying or talking about something else.

    However, you can access the private method getInt of whatever subclass is invoking printInt like so:

    public void printInt() throws Exception {
        Class clazz = getClass();
        System.out.println("I am " + clazz + ". The int is " +
                           clazz.getMethod("getInt").invoke(this) );
    }
    

    This will have the effect of the subclass' getInt method being called from the superclass' printInt. Of course, now this will fail if the subclass doesn't declare a getInt, so you have to add a check to be able to handle "normal" subclasses that don't try to "override" a private method:

    public void printInt() throws Exception {
        Class clazz = getClass();
    
        // Use superclass method by default
        Method theGetInt = SuperClass.class.getDeclaredMethod("getInt");
    
        // Look for a subclass method
        Class classWithGetInt = clazz;
        OUTER: while( classWithGetInt != SuperClass.class ){
    
            for( Method method : classWithGetInt.getDeclaredMethods() )
                if( method.getName().equals("getInt") && method.getParameterTypes().length == 0 ){
                    theGetInt = method;
                    break OUTER;
                }
    
            // Check superclass if not found
            classWithGetInt = classWithGetInt.getSuperclass();
        }
    
        System.out.println("I am " + classWithGetInt + ". The int is " + theGetInt.invoke(this) );
    }
    

    You still have to change superclass code to make this work, and since you have to change superclass code, you should just change the access modifier on getInt to protected instead of doing reflection hack-arounds.

提交回复
热议问题