Java 中是否强制执行密封类?如果是,如何执行?

发布于 2024-10-07 14:00:53 字数 250 浏览 3 评论 0原文

可以在 Scala 中定义密封类,这些类基本上是final,除非子类发生在同一个文件中。

JVM 似乎不允许 final 类字节码及其子类。

考虑到字节码中没有源文件的“概念”,这个限制是如何强制执行的?

因此,javac 如何防止 Scala sealed 类在 Java 中被子类化?

It is possible to define sealed classes in Scala, which are basically final except if the sub-classing happens in the same file.

It seems that the JVM doesn't allow final class bytecode and subclasses of it.

Considering that there is no "notion" of source file in the bytecode, how is this restriction enforced?

Therefore, how can javac prevent a Scala sealed class from being sub-classed in Java?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

素衣风尘叹 2024-10-14 14:00:53

该限制由 scalac 在编译时对 Scala 源强制实施。生成的二进制类定义没有设置 JVM 最终标志,因此,正如您现在可能已经猜到的那样,当针对 Scala 二进制文件编译 Java 源代码时,javac 不会强制执行密封限制。

The restriction is enforced for Scala source by scalac at compile time. The resulting binary class definitions don't have the JVMs final flag set so, as you've probably guessed by now, the sealed restriction will not be enforced by javac when Java sources are compiled against Scala binaries.

风流物 2024-10-14 14:00:53

如何为要密封的类使用私有构造函数,然后创建扩展该类的公共最终静态内部类。然后,您在编译时获得一组固定的子类,无法进一步扩展。具有私有构造函数的基类随后充当到达这些内部类的路径,但其本身不可能在其他地方扩展和实现。

How about using a private constructor for the class you would like to seal, and then create public final static inner classes that extends that class. Then you get a fixed set of subclasses at compile time that can't be extended further. The base class with the private constructor subsequently serves as a path to reach those inner classes, but is in itself impossible to extend and implement elsewhere.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文