Java Marker Interface(在java与模式一书中翻译作 标识接口)
Java Marker Interface Examples
- java.lang.Cloneable
- java.io.Serializable
- java.util.EventListener
Is Runnable a marker interface?
First point, there is no reference or definition about marker interface from Java specification/api. This is yet another inconclusive debate. ‘Marker Interface’ is a term coined by (book / web) authors. Since we don’t have Java’s definition it is left to us to arrive at a decent definition. This is one popular question asked in java interview. My answer to the interviewer, there are better questions ask than this to ask.“Runnable is not a marker interface”, you might say ‘run’ is used to start a method and this is a special instruction to the JVM. When you run a java class the java interpreter calls the ‘main’ method, because of this would you say every java class as “marker class”?
‘My’ definition for marker interface
“An interface is called a marker interface when it is provided as a handle by java interpreter to mark a class so that it can provide special behaviour to it at runtime and they do not have any method declarations”.
In the above definition “and they do not have any method declarations” is added because, till now all the marker interfaces provided by java do not have method declarations. I dont think, in future there will be any new marker interfaces added :-)
We cannot create marker interfaces, as you cannot instruct JVM to add special behavior to all classes implementing (directly) that special interface.
网上找了一个例子;
package test1;
interface SomeThing{}
interface Human extends SomeThing{}
interface Animal extends SomeThing{}
class Chinese implements Human{}
class Japanese {}
class Dog implements Animal{}
class Monster implements Human{}
public class Hunter{
public void fire(Object obj){
if(obj instanceof Human) return;
System.out.println("fire the target" + obj.getClass().getName());
}
public static void main(String[] args) {
Hunter hunter = new Hunter();
Object[] objs = new Object[]{new Dog(), new Japanese(), new Chinese(), new Monster(), new SomeThing(){}};
for(int i=0; i<objs.length;i++){
hunter.fire(objs[i]);
}
}
}
说明这种关系,通过Human标记来判断 目标是否应该开枪,如果是Human的接口实现者,即便是妖怪Monster也不开枪,但即便是人,javanese,但是由于没有实现标记接口,照样开枪。
注意 标记接口这个概念在 官方文档中没有出现,是网络上 或是 出书的人为了 描述这种接口设计 所杜撰出来的一个概念。
例子参看网页:http://www.189works.com/article-14205-1.html