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.

  • 相关阅读:
    模拟实现atoi函数
    C语言中的字符串函数的实现,strcpy,strlen,strcat,strcmp
    使用repeater实现gridview的功能
    使用NPOI随意创建Excel(含下拉列表)
    使用存储过程来动态调用数据(SELECT)
    判断sql执行效率以及针对临时表的使用
    C#读取Excel显示到repeater中
    ASP.NET使用后台更改前台Style
    js格式化日期
    查询某张表的表结构
  • 原文地址:https://www.cnblogs.com/haokaibo/p/Use-marker-interfaces-to-define-types.html
Copyright © 2011-2022 走看看