如果第三方库类中的method()调用super.method,如何重写它



我本想调用super.super.method(),但在java中无法做到这一点。有几个问题和很多答案这个但在这种情况下,没有一个是有效的
这不是一个"糟糕的设计";或者破坏封装。我有一个真正的用例,我需要覆盖第三方类,因为它有一个bug,我正在寻找一个好的解决方案。

因此,我正在寻求解决方案的情况是:
classContextGetter和SpecialContextGetter在第三部分类库中。SpecialContextGetter中的getContext方法有一个错误(它将i设置为8而不是7)。

我想把它修好。因此,我用SpecialContextGetterCorrected扩展了SpecialContextGetter,在其中我重新实现了getContext(从SpecialContextGeter复制并进行了更改)并指示框架使用我的类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 */
}

我看到了几个选项,如果第三方软件的可见性声明过于严格,这两个选项可能都不可行。

  • 复制/粘贴整个SpecialContextGetter类并修复那里的错误,而不是扩展SpecialContextGetter并只覆盖罪魁祸首方法。这可能很难看,这是唯一的办法
  • 不是扩展SpecialContextGetter,而是扩展ContextGetter并委托给SpecialContextGetter的一个实例(您将在这个新类的构造函数中收到),用于所有方法,除了您希望修复错误的方法(您可以访问所需的super)。如果幸运的话,你可能会这样做,但我有一种感觉,一些可见性声明或可变状态不允许你这样做

最新更新