本文介绍了覆盖方法的内部行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个实现方法 doBlah 的类 A .我有一个类 B ,它继承了 A 的子类,并且具有 @Override 方法 doBlah .在 B.doBlah 中执行一些简单的操作后,我将调用 A.doBlah .

There is a class A that implements a method doBlah. I have a class B that subclasses A and has an @Override method doBlah. After I perform some simple manipulation in B.doBlah, I call A.doBlah.

A.doBlah 调用静态方法 C.aStaticMethod .

A和C是我无法修改的外部库的一部分.

A and C are part of an external library I can't modify.

Id喜欢有一个由 A.doBlah 调用的静态方法 CC.aStaticMethod 代替 C.aStaticMethod .使用任何设计模式/技巧都可以吗?

Id like to have a static method CC.aStaticMethod called by A.doBlah in place of C.aStaticMethod. Would this be possible using any design patterns/hacks?

我确实有 A 的源代码,并且可以将其中的文件包含到我的代码中,并根据需要进行修改等.但是,我不能这样修改 A 包.

I do have the source to A and I can include files from them into my code and modify etc if required. However, I cant modify the A package as such.

推荐答案

如果您无法修改 A C ,并调用 A 直接,答案是.

If you can't modify A or C, and call A directly, the answer is no.

如果另一方面,如果您不需要直接调用 A.doBlah ,则可以覆盖其行为(前提是该方法不是final ),然后在您自己的类中调用 CC.aStaticMethod .

If, on the other hand, you don't need to call A.doBlah directly, you can override it's behavior (provided the method is not final), in your own class, and have it call CC.aStaticMethod.

如果您确实有权访问源代码,则可以进行非常非常丑陋的修改:

If you do have access to the source, you can do a very, very ugly hack:

在与原始包完全相同的包中创建类 A ,并修改方法 doBlah 以调用所需的内容.

Create a class A in exactly the same package as the original, and modify the method doBlah to call what you need.

请记住,这有很多缺点,即,如果 A 属于外部库,则您无法知道对该库的更新是否会破坏您的代码,因为您将运行 A 的旧版本.基本上是说这种方法可能很快变成维护的噩梦.

Keep in mind that this has quite a few drawbacks, namely, if A belongs to an external library, you have NO way of knowing if an update to that library will break your code or not, since you'll be running an older version of A. This is basically to say that this approach can turn quickly into a maintenance nightmare.

这篇关于覆盖方法的内部行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 03:11