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.

  • 相关阅读:
    iOS10权限声明国际化
    用"僵尸对象"调试内存管理问题
    windows系统下的两个批处理命令
    解决windows系统下打开应用弹出丢失libmysql.dll的问题
    简单的cocos2dx笔试题
    解决cocos2dx 3.x 导入cocostudio的ui界面出现错位问题
    mac 使用homebrew 安装mysql
    cocos2dx for lua 简单的翻牌动画
    cocos2dx for lua A*寻路算法实现2
    解决升级mac os X EI Capitan后遇到LibclangError: dlopen(libclang.dylib, 6): image not found.的问题
  • 原文地址:https://www.cnblogs.com/haokaibo/p/Use-marker-interfaces-to-define-types.html
Copyright © 2011-2022 走看看