How to write our own marker interface in Java?

前端 未结 6 856
遇见更好的自我
遇见更好的自我 2021-02-04 06:15

I know marker interface in java. It is used to define a specific behaviour about a class. For example, Serializable interface has the specific ability to store an object into by

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-04 06:54

    As explained very nicely in the Wikipedia article Marker interface pattern, a marker interface is a form of metadata. Client code can test whether an object is an instance of the marker interface and adapt its (the client's) behavior accordingly. Here's a marker interface:

    public interface CoolObject {
    }
    

    Then code can test whether an object is a CoolObject and do something with it:

    if (anObject instanceof CoolObject) {
        addToCoolList((CoolObject) anObject);
    }
    

    The Serializable interface is defined as part of the Java language. You cannot implement behavior at that level yourself.

    You can add methods to a marker interface, but that mixes the marker pattern with other conceptual uses for interfaces and can be confusing. (Is a class implementing the interface for the purposes of marking it, or for its behavior, or both?)

    As explained in the Wikipedia article, marker interfaces in Java can (and probably should) be replaced with annotations.

提交回复
热议问题