Question

In c++ you can easely call eny oveloaded method from any previus parent classes. How an i do somethink like that in Java?

Example:

class A {

    public void f() {
        System.out.println("A");
    }

};

class B extends A {

    @Override
    public void f() {  
        super.f();
        System.out.println("B");
    }

};

class C extends B {

    @Override
    public void f() {  
        super.f(); // how to invoke f() method of A class avoiding B class?
        System.out.println("C");
    }

};

So calling c.f() will print "ABC".

How to call from C class method of A class avoiding same overloaded method of B class?

Was it helpful?

Solution 2

As others have already pointed out, you can't get it directly (For example super.super. doesn't work).

Here is a hack you can mess around with:

try
{
    Class<?> s = this.getClass();
    while ( !"java.lang.Object".equals(s.getSuperclass().getName())  )
    {
        s = s.getSuperclass();
    }
    Method m = s.getMethod(Thread.currentThread().getStackTrace()[1].getMethodName(), (Class<?>[])null);
    if ( m != null )
    {
        m.invoke(s.newInstance()); // This is the actual call to the 'super' method.
    }
}
catch ( Exception e )
{
    e.printStackTrace();
}

It's not pretty, but for simple classes and methods it works ;)

ps. This hack only supports methods without any parameters. If you need to support parameters you'll need to use the getMethods() method. Also, if the final "superclass" doesn't support the method it'll also not work, but you can add code in the while loop to check that and catch the last superclass that does support it.

OTHER TIPS

In Java you can't do this without a hack because C is a B not just an A. If you can do this in C++, it's a bad idea IMHO. This suggests your hierarchy is messed up and C should be only an A not a B.

If you really have to do this you can add a method to B like this so you can bypass B.f();

protected void superF() {
    super.f();
}

and call this from C.


It is possible to generate the byte code using ASM to do this. The byte code allows you to call any level of parent, it is Java which does not.

No this can't be done in java. However if you want it to be done create an instance of class A in overridden method f() of class C and invoke f() of class A using the object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top