开发者

Call method in class even if it has been overridden in a subclass (java)

开发者 https://www.devze.com 2023-02-21 19:03 出处:网络
Suppose that I have this method: public void callDo(FeelFreeToExtend ext){ ext.do() } Where FeelFreeToExtend is this:

Suppose that I have this method:

public void callDo(FeelFreeToExtend ext){
    ext.do()
}

Where FeelFreeToExtend is this:

public class FeelFreeToExtend {

    public void do(){
       System.out.println("DO");
    }

}

Now I know that someone could override the do method but is there a way that I can explicitly call the do method开发者_Go百科 in the FeelFreeToExtend class? I don't think that this would ever be a great idea however it is still interesting.


No, it is not possible without changing the bytecode/code of all the callers. If you want to always call the FeelFreeToExtend.do() make the method final.


Append the non-access qualifier "final" to the method (make the method final), this will stop the method from being overridden and hence this version of the method will be called always from any of the subclasses.

Secondly, if you just want to access a super class method from a derived class even if the super class method has been overridden then just call the method by appending "super." before the method call.For eg. to call the method "display" of a super class from a subclass, use super.display(). (This assumes that you are the one coding the sub class)


Actually what Peter says is not completely correct: in fact it is possible to execute an overridden method using JNI (http://java.sun.com/docs/books/jni/html/fldmeth.html#26109). In JNI there are method called CallNonvirtual<Type>Method allowing exactly that.

Application servers or frameworks could be shipped with a small JNI utility to allow this kind of features...

Without JNI I don't think this is possible.

0

精彩评论

暂无评论...
验证码 换一张
取 消