标记接口 [英] Marker Interfaces

查看:41
本文介绍了标记接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释一下Java中标记接口的约定吗?

Could somebody pls explain the contract of marker interfaces in java?

对于Ex:如果 Clonable 是没有字段/方法的标记接口,那么 clone()定义在哪里?

For Ex: If Clonable is a Marker Interface with no fields/methods, then where is the clone() defined?

为什么每当使用 clone()时,我们都应该实现 Clonable i/f?

Why should we implement Clonable i/f whenever clone() is used?

我的问题是,如果 clone() java.lang.Object 类的方法,为什么要实现 Clonable i/f覆盖 clone().

Well my question was, if clone() is a method of java.lang.Object class, why implement Clonable i/f to override clone().

有人可以详细说明一下Java的这种约定吗?

Could somebody elaborate on this convention of java ?

预先感谢

推荐答案

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.

这篇关于标记接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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