且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

标记接口

更新时间:2023-01-07 14:01:21

clone()在所有类的 java.lang.Object 类中定义,但是受保护.这实际上是一个具体的方法实现,它对对象进行逐字段克隆,但前提是您已经实现了 Cloneable 接口以表明允许这样做.

clone() is defined in the java.lang.Object class which all classes extend from, however it is protected. This is actually a concrete method implementation that does a field by field clone of the object, but only if you've implemented the Cloneable interface to indicate this is allowed.

实际上,许多人会覆盖 clone()方法,以便可以将其设置为 public ,并允许从类外部进行克隆.

In practice many people override the clone() method so that they can make it public and allow cloning from outside the class.

整个模式非常不寻常,不是您通常会复制的东西,我想不出JVM中有很多标记接口和方法配对的其他示例.从 Java 5 开始,***对标记使用注释.例如用于将类型标记为Jax-B可序列化(在Java 5之后)的 @XmlRootElement 与用于指示类是二进制可序列化的 Serializable 接口(在Java 5之前).

This whole pattern is quite unusual and not something you would usually replicate, I can't think of many other examples in the JVM where there is a paired marker interface and method. From Java 5 onwards it's better to use annotations for markers. e.g. the @XmlRootElement used to mark a type as Jax-B serializable (post Java 5) vs the Serializable interface (pre Java 5) used to indicate a class is binary serializable.