Могу ли я переопределить закрытый метод в Java?

Я знаю, что могу использовать рефлексию для вызова закрытого метода и для получения или установки значения закрытой переменной, но я хочу переопределить метод.

public class SuperClass {

    public void printInt() {
        System.out.println("I am " + getClass() + ". The int is " + getInt());
    }

    private int getInt() {
        return 1;
    }
}

public class SubClass extends SuperClass {

    public static void main(String[] args) {
        (new SubClass()).printInt();
    }

    public int getInt() {
        return 2;
    }
}

Я хочуmain метод вSubClass  распечатать2, но это распечатывает1. I've heard this can be done through reflection, but I can't figure out how. If not reflection, does anyone know of another way of doing it? (Other than making SuperClass.getInt() защищены, или копирование и вставкаprintInt() метод вSubClass.) If actually overriding the private method is not possible, is there a way of placing some sort of trigger on it that will invoke a method in my sub-class either before or after the private method executes?

Ответы на вопрос(10)

Error: User Rate Limit Exceeded

Error: User Rate Limit ExceededprivateError: User Rate Limit ExceededprivateError: User Rate Limit Exceeded

Error: User Rate Limit ExceededoverriddenError: User Rate Limit Exceededfrom within the subclassError: User Rate Limit ExceededoverridingError: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

  • there is no method with a matching signature in the superclass

Error: User Rate Limit Exceeded

  • the method in the superclass that you are trying to override is marked private or final

Error: User Rate Limit ExceededError: User Rate Limit ExceededError: User Rate Limit Exceeded

Instance Methods

...The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed.... When overriding a method, you might want to use the @Override annotation that instructs the compiler that you intend to override a method in the superclass. If, for some reason, the compiler detects that the method does not exist in one of the superclasses, then it will generate an error.

Error: User Rate Limit ExceededprivateError: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

class Super
{
   private void fun()
   {
   }
}

class Child extends Super
{
    private void fun()
    {
    }
}

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

class PrivateTest { 

private String msg = "OuterAndInner";

private void fun() {
     System.out.println("Outer fun()");
}

class Inner extends PrivateTest {
    private void fun()  {
          System.out.println("Accessing Private Member of Outer: " + msg);
    }
}
public static void main(String args[])  {
     PrivateTest o = new PrivateTest();
     Inner  i   = o.new Inner();
     i.fun();
     // o.fun() calls Outer's fun (No run-time polymorphism).
     o = i; 
     o.fun();
}

}

Решение Вопроса

Error: User Rate Limit Exceeded

Error: User Rate Limit ExceededgetIntError: User Rate Limit ExceededprintIntError: User Rate Limit Exceeded

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

Error: User Rate Limit ExceededgetIntError: User Rate Limit ExceededprintInt. Of course, now this will fail if the subclass doesn'tError: User Rate Limit ExceededgetIntError: User Rate Limit Exceeded

public void printInt() throws Exception {
    Class<? extends SuperClass> 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) );
}

Error: User Rate Limit ExceededgetIntError: User Rate Limit ExceededprotectedError: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit ExceededError: User Rate Limit ExceededError: User Rate Limit ExceededError: User Rate Limit ExceededError: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

public class SuperClass {

    private final Method getInt;

    public SuperClass() {
        /** Find the appropriate method to call and cache it. **/
        Method getInt = null;
        try {
            getInt = getClass().getDeclaredMethod("getInt");
        }
        catch (NoSuchMethodException e) {
            try {
                getInt = SuperClass.class.getDeclaredMethod("getInt");
            } catch (NoSuchMethodException e1) {
                throw new RuntimeException(e1);
            }
        }
        getInt.setAccessible(true);
        this.getInt = getInt;
    }

    public void print() {
        int val = 0;
        try {
            val = (Integer) getInt.invoke(this);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        System.out.println(val);
    }

    private int getInt() {
        return 1;
    }
}

public class SubClass extends SuperClass {
    public int getInt() {
        return 2;
    }

    public static void main(String[] args) throws Exception {
        new SubClass().print();
    }
}

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit ExceededlookError: User Rate Limit Exceeded

public class Test {

    public static class Superclass {
        private void foo() {
            System.out.println("Superclass.foo");
        }
    }

    public static class Subclass extends Superclass {
        private void foo() {
            System.out.println("Subclass.foo");
            // Looks like it shouldn't work, but does...
            super.foo();
        }
    }

    public static void main(String[] args) throws Exception {
        Superclass x = new Subclass();
        // Only calls Superclass.foo...
        x.foo();
    }
}

Error: User Rate Limit ExceededonlyError: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceededprivate.

Error: User Rate Limit Exceededfinal.

Error: User Rate Limit ExceededprivateError: User Rate Limit Exceeded

Ваш ответ на вопрос