相当于在Java中扩展最终类 [英] Equivalent to extending a final class in Java

查看:323
本文介绍了相当于在Java中扩展最终类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在Java中我们无法扩展最终的类。但是有没有其他方法可以让我获得延伸最终课程的效果?

I know that in Java we can't extend a final class. But is there any alternative way where I get the effect of extending a final class?

因为我有一个最后的课程,我正在寻找的要求,所以如果不知何故我可以重用它,对我来说会有很大帮助。

Because I have a final class with the requirements I am looking for, so if somehow I can reuse this, it would be of great help for me.

推荐答案

为最终类创建一个包装器?

Create a wrapper for the final class?

这样的事情:

class MyClass {
    private FinalClass finalClass;

    public MyClass {
        finalClass = new FinalClass():
    }

    public void delegatingMethod() {
        finalClass.delegatingMethod();
    }
}

包装类,如 MyClass 将不被接受为 FinalClass 的实例。如果 FinalClass 实现任何接口,您可以在 MyClass 中实现它们,以使类更相似。 FinalClass 的任何非最终父母也是如此;在这种情况下,你的 MyClass 设计应该与那些父类兼容。

A wrapper class like MyClass won't be accepted as an instance of FinalClass. If FinalClass implements any interfaces you can implement them in MyClass to make the classes more alike. The same is true of any non-final parents of the FinalClass; in that case your MyClass design should be compatible with those parent classes though.

甚至可以在运行时使用反射创建包装类。在这种情况下,您可以使用 代理。请注意,代理类确实需要深入了解Java类型系统。

It is even possible to create a wrapper class during runtime using reflection. In that case you can use the Proxy class. Beware that proxy classes do require in depth knowledge about the Java type system.

这篇关于相当于在Java中扩展最终类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆