如何在 Java 中扩展 final 类 [英] How to extend a final class in Java
问题描述
这是我现在面临的问题.我有一个类,比如说 Foo
,这个类定义了一个名为 getBar
的方法,它返回一个 Bar
实例.Bar
类定义在 Foo
中,并声明为 public static final
.我想要做的是定义一个扩展 Foo
的类 MyFoo
但我也想用 MyBar
扩展 Bar
> 通过添加我自己的功能(方法、属性等).我还希望 getBar
返回 MyBar
.
Here is my problem actually I'm facing now.
I have a class, let's say Foo
and this class defines a method called getBar
that returns a Bar
instance. The class Bar
is defined inside Foo
and and is declared public static final
. What I want to do is to define a class MyFoo
that extends Foo
but I also want to extend Bar
with MyBar
by adding my own functionalities (methods, properties,etc).
I also want getBar
to return MyBar
.
问题是 Bar
是最终的.这是我想做的事情的说明:
The problem is Bar
is final. Here is an illustration of what I want to do :
public class Foo {
Bar bar = new Bar();
public Bar getBar(){
return bar;
}
....
public static final class Bar {
}
}
我想做的是:
public class MyFoo extends Foo {
public MyBar getBar(){ // here I want to return an instance of MyBar
}
public static final class MyBar extends Bar { // That's impossible since Bar is final
}
}
我怎样才能做到这一点?
How can I achieve that?
我正在为我的问题添加更多细节.我实际上正在为 Jenkins 开发一个插件,经过搜索,我意识到有一个插件可以提供我想要做的基本功能,Foo
和 Bar
.我想自定义 Foo
和 Bar
,所以它可以满足我的需求.Foo 是插件的主类,并扩展了一个名为 Builder 的类.Foo 定义了一个名为 perform
的方法,它包含执行构建的所有操作.Bar
包含用于配置目的的操作,Foo 需要 Bar 来获取这些信息.
I am adding more details to my question.
I am actually developing a plugin for Jenkins and after searching, I realize there is a plugin that offers the base functionalities that I want to do, Foo
and Bar
. I want to custom Foo
and Bar
, so it can fits my needs.
Foo is the main class of the plugin and extends a class called Builder. Foo defines a method called perform
which contains all the operations for performing a build.
Bar
contains operations for configurations purposes and Foo needs Bar to get those informations.
所以我想做的是用 MyFoo
扩展 Foo 并用 MyBar
添加一些配置.如您所见,MyFoo
需要通过调用 getBar();
So what I want to do is to extend Foo with MyFoo
and add some configurations with MyBar
. And as you see, MyFoo
will need to get those configuations by calling getBar();
第二件事是我无法控制 MyFoo
和 MyBar
The second thing is I have no control of the instanciation of MyFoo
and MyBar
阻碍我的是我无法扩展 Bar.我怎样才能做到这一点?
What blocks me, is that I cannot extend Bar. How can I achieve that?
推荐答案
基本上你不能.看起来设计 Bar
的开发人员打算让它不被扩展 - 所以你不能扩展它.您需要寻找一种不同的设计——可能是一种不太使用继承的设计……当然,假设您无法更改现有代码.
You can't, basically. It looks like the developer who designed Bar
intended for it not to be extended - so you can't extend it. You'll need to look for a different design - possibly one which doesn't use inheritance so much... assuming you can't change the existing code, of course.
(如果不了解这里的真正目标 - 整个系统的设计,就很难给出更具体的建议.)
(It's hard to give more concrete advice without knowing more about the real goal here - the design of the overall system.)
这篇关于如何在 Java 中扩展 final 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!