If a Marker Interface does not have any methods, how does it work?

后端 未结 5 1917
长情又很酷
长情又很酷 2020-11-27 21:08

I am aware of what marker interface is and when we need to use it. One question is still not clear to me. If a marker interface does not have any method or body, how does

相关标签:
5条回答
  • 2020-11-27 21:26

    Marker interface in Java is interfaces with no field or methods or in simple word empty interface in java is called marker interface. e.g. serializable, Clonnable and Remote Interface. They are used to indicate signal or command to the compiler Or JVM. It can also be used to classify code. You can also write your own marker interface and use them to logically divide your code. Also, you can write any pre-processing operation on those class.

    0 讨论(0)
  • 2020-11-27 21:30

    A marker interface tells JVM that the class being marked by marker interface to add functionality of a marker interface . Like implementing Cloneable tells JVM that this class implements Cloneable and hence JVM will have to copy it bit-wise.

    0 讨论(0)
  • 2020-11-27 21:35

    The only useful thing you can do with it is

    if (instance instanceof MyMarkerInterface) {
       ...
    }
    
    0 讨论(0)
  • 2020-11-27 21:44

    Marker interfaces can be replaced with annotations in many places, however a marker interfaces can still be used for

    • The compile time checks. You can have a method which must take an object of a class with a given marker interface(s) e.g.

      public void myMethod(MyMarkerInterface MMI);
      

    You cannot have this compile time check using an annotation alone.

    BTW: You can have two interfaces using generics, but good examples are rare.

    • Support frameworks which depend on interface(s) to identify a component type. like OSGi.

    EDIT: I use this for a Listener marker interface. A listener has methods methods marked with annotations but the methods can have any name or type. It adds a compiler time check to what would otherwise be a purely runtime linking.

    public Component implements Listener {
    
    @ListenerCallback
    public void onEventOne(EventOne... eventOneBatch) { }
    
    @ListenerCallback
    public void onEventTwo(EventTwo eventTwo) { }
    }
    
    0 讨论(0)
  • 2020-11-27 21:51

    A marker interface doesn't "work" as such. As the name suggests, it just marks a class as being of a particular type. Some other code has to check for the existence of the marker and do something based on that information.

    These days annotations often perform the same role that marker interfaces did previously.

    0 讨论(0)
提交回复
热议问题