我可以覆盖一个隐藏(但公众)方法,并调用其超强的方法?方法、公众

2023-09-07 17:58:52 作者:一步踏尽一树白

有一个非公开的API,我需要为了要解决与Android的WebView中一个怪癖覆盖。

API是隐藏的,但它是公共的:

  / ** * ... * * @hide未决API国务院批准 * /公共布尔selectText(){    ...} 

所以,我可以通过简单地在自己的WebView类声明它覆盖它,减去@覆盖:

 公共布尔selectText(){    ...} 
只想着一直调用一直爽, 那API凭证泄漏风险如何破

是否有可能调用从我重写超级方法?通常情况下我可以写:

 公共布尔selectText(){    返回super.selectText();} 

但这种方法是隐藏的,所以 super.selectText()不可用。如果我使用反射:

 公共布尔selectText(){    回报(布尔)WebView.class.getMethod(selectText)调用(这一点,(对象[])为空)。} 

我得到一个无限循环,因为它叫我重写的方法。

反正是有覆盖这个方法,并能够调用超级方法?

谢谢!

解决方案   

反正是有覆盖此方法并能够调用超  方法是什么?

没有,不幸的是,在回答解释的问题How使用Java反射来调用父类的方法你不能用反射解决这个问题。

There is a non public api that I need to override in order to workaround a quirk with Android's WebView.

The api is hidden but it is public:

/**
 * ...
 *
 * @hide pending API council approval
 */
public boolean selectText() {
    ...
}

So I can override it by simply declaring it in my own WebView class, minus the @Override:

public boolean selectText() {
    ...
}

Is it possible to call the super method from my override? Normally I could write:

public boolean selectText() {
    return super.selectText();
}

But the method is hidden, so super.selectText() is not available. If I use reflection:

public boolean selectText() {
    return (Boolean) WebView.class.getMethod("selectText").invoke(this, (Object[]) null);
}

I get an infinite loop because it calls my overridden method.

Is there anyway to override this method AND be able to call the super method?

Thanks!

解决方案

Is there anyway to override this method AND be able to call the super method?

No, unfortunately, as is explained in the answer to the question How to call a superclass method using Java reflection you cannot solve this problem with reflection.