zoukankan      html  css  js  c++  java
  • Effective Java 37 Use marker interfaces to define types

    Marker interface is an interface that contains no method declarations, but merely designates (or "marks") a class that implements the interface as having some property.

    Such as Serializable interface which indicates that the instance implements it can be the argument of the method ObjectOutputStream.write(Object) correctly. Or the Set interface which implements Collection interface by just implementing all the methods of Collection without adding new method.

    Differences

    Marker Interface

    Marker annotation

    Define a type that is implemented by instances of the marked class

    Y

    N

    It's possible to add more information to an annotation type after it is already in use.

    N

    Y

    Applies to any program element other than a class or interface, as only classes and interfaces can be made to implement or extend an interface.

    N

    Y

    Mark classes and interfaces

    Y

    N

       

    Note

    If the marker applies only to classes and interfaces, ask yourself the question, Might I want to write one or more methods that accept only objects that have this marking? If so, you should use a marker interface in preference to an annotation. This will make it possible for you to use the interface as a parameter type for the methods in question, which will result in the very real benefit of compile-time type checking.

       

    If you answered no to the first question, ask yourself one more: Do I want to limit the use of this marker to elements of a particular interface, forever? If so, it makes sense to define the marker as a subinterface of that interface. If you answered no to both questions, you should probably use a marker annotation

       

    Summary

    If you find yourself writing a marker annotation type whose target is ElementType.TYPE, take the time to figure out whether it really should be an annotation type, or whether a marker interface would be more appropriate.

  • 相关阅读:
    公钥,私钥和数字签名这样最好理解
    SolrCloud的官方配置方式
    由于Windows和Linux行尾标识引起脚本无法运行的解决
    python模块名和文件名冲突解决
    Linux下编译安装python3
    Storm集群的安装配置
    Linux下编译安装Apache 2.4
    SELinux的关闭与开启
    Spring MVC配置静态资源的正常访问
    SolrCloud环境配置
  • 原文地址:https://www.cnblogs.com/haokaibo/p/Use-marker-interfaces-to-define-types.html
Copyright © 2011-2022 走看看