Java 中是否强制执行密封类?如果是,如何执行?
可以在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该限制由 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.
如何为要密封的类使用私有构造函数,然后创建扩展该类的公共最终静态内部类。然后,您在编译时获得一组固定的子类,无法进一步扩展。具有私有构造函数的基类随后充当到达这些内部类的路径,但其本身不可能在其他地方扩展和实现。
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.