[英]How do you override method() in third party library class if it calls super.method?
我本來想調用 super.super.method() 但你不能在 java 中這樣做。 並且有幾個問題和很多像這樣的答案,但在這種情況下沒有一個會起作用。
這不是“糟糕的設計”或破壞封裝的問題。 我有一個真正的用例,我需要覆蓋第三方類,因為它有一個錯誤,我正在尋找一個好的解決方案。
所以我正在尋求解決方案的情況是這樣的:
類 ContextGetter 和 SpecialContextGetter 在第三方類庫中。 SpecialContextGetter 中的 getContext 方法有一個錯誤(它將 i 設置為 8 而不是 7)。
我想修復它。 所以我用 SpecialContextGetterCorrected 擴展了 SpecialContextGetter,在其中我重新實現了 getContext(從 SpecialContextGetter 復制它並進行了更改)並指示框架使用我的類 SpecialContextGetterCorrected,而不是 SpecialContextGetter。
問題是我的新方法仍然需要調用 ContextGetter.getContext 並且我不能告訴 Java 這樣做。 (我想調用 super.super.getContext)
如果不將我自己的 com.thirdparty.SpecialContextGetter 放在類路徑前面,我該如何完成呢?
package com.thirdparty;
class ContextGetter {
//has several state variables
public Context getContext(Set x) throws Exception {
/* uses the state vars and its virtual methods */
/* may return a Context or throw an Exception */
}
/* other methods, some overridden in SpecialContextGetter */
}
class SpecialContextGetter extends ContextGetter {
//has several state variables
public Context getContext(Set x) throws Exception {
/* uses the state vars and its virtual methods */
/* somewhere in it it contains this: */
if (isSomeCondition()) {
try {
// *** in my copied code i want to call super.super.getContext(x) ***
Context ctxt=super.getContext(x);
/* return a modified ctxt or perhaps even a subclass of Context */
} catch( Exception e) {
/* throws new exceptions as well as rethrows some exceptions
depending on e and other state variables */
}
else {
/* some code */
int i=8; // *** this is the bug. it should set i to 7 ***
/* may return a Context or throw an Exception */
}
}
/* other methods, some overridden in SpecialContextGetter */
}
我看到了幾個選項,如果 3rd 方軟件的可見性聲明太嚴格,這兩個選項都可能不可行。
SpecialContextGetter
並僅覆蓋罪魁禍首方法,而是復制/粘貼整個SpecialContextGetter
類並修復那里的錯誤。 這可能很難看,唯一的辦法。ContextGetter
SpecialContextGetter
SpecialContextGetter
可以訪問super
你想要的。 如果你很幸運,你可能會這樣做,但我感覺一些可見性聲明或可變狀態不會讓你這樣做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.