`
leonzhx
  • 浏览: 788643 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Item 29: Consider typesafe heterogeneous containers

阅读更多

1.  Generic containers limit you to a fixed number of type parameters per container. In some cases we may parameterize the key instead of the container. Then present the parameterized key to the container to insert or retrieve a value. The generic type system is used to guarantee that the type of the value agrees with its key:

// Typesafe heterogeneous container pattern - implementation
public class Favorites {
    private Map<Class<?>, Object> favorites = new HashMap<Class<?>, Object>();
    public <T> void putFavorite(Class<T> type, T instance) {
        if (type == null)
            throw new NullPointerException("Type is null");
        favorites.put(type, instance);
    }
    
    public <T> T getFavorite(Class<T> type) {
        return type.cast(favorites.get(type));
    }
}

 

A Favorites instance is typesafe: it will never return an Integer when you ask it for a String. It is also heterogeneous: all the keys are of different types. We call Favorites a typesafe heterogeneous container. When a class literal is passed among methods to communicate both compile-time and runtime type information, it is called a type token.

 

2.  The type of a class literal is no longer simply Class, but Class<T>. For example, String.class is of type Class<String>, and Integer.class is of type Class<Integer>.

 

3.  The Class.cast method is the dynamic analog of Java’s cast operator. It simply checks that its argument is an instance of the type represented by the Class object. If so, it returns the argument; otherwise it throws a ClassCastException.

 

4.  A malicious client could easily corrupt the type safety of a Favorites instance, simply by using a Class object in its raw form. But the resulting client code would generate an unchecked warning when it was compiled. This is no different from putting a String into a HashSet<Integer> by using the raw type HashSet. To resolve this issue:

// Achieving runtime type safety with a dynamic cast
public <T> void putFavorite(Class<T> type, T instance) {
    favorites.put(type, type.cast(instance));
}

 

5.  There are collection wrappers in java.util.Collections that play the same trick. They are called checkedSet, checkedList, checkedMap, and so forth. Their static factories take a Class object (or two) in addition to a collection (or map). The static factories are generic methods, ensuring that the compile-time types of the Class object and the collection match. The wrappers add reification to the collections they wrap. (The wrapper throws a ClassCastException at runtime if someone tries to put Coin into your Collection<Stamp>.)

 

6.  An AnnotatedElement is a typesafe heterogeneous container whose keys are annotation types, it contains the following method:

public <T extends Annotation> T getAnnotation(Class<T> annotationType);

 

7.  You could cast the object of Class<?> to Class<? extends Annotation>, but this cast is unchecked. The class Class provides an instance method that performs this sort of cast safely (and dynamically). The method is called asSubclass, and it casts the Class object on which it’s called to represent a subclass of the class represented by its argument. If the cast succeeds, the method returns its argument; if it fails, it throws a ClassCastException.

 

分享到:
评论

相关推荐

    Effective Java 3rd edition(Effective Java第三版英文原版)附第二版

    Item 33: Consider typesafe heterogeneous containers 6 Enums and Annotations Item 34: Use enums instead of int constants Item 35: Use instance fields instead of ordinals Item 36: Use EnumSet instead of...

    配置:用于Typesafe配置的Scala包装器

    import com . typesafe . config . ConfigFactory import configs . ConfigReader 从config获取值的结果类型是configs.Result 。 如果成功,则返回configs.Result.Success ,如果不成功,则返回configs.Result....

    k9r:用于Typesafe项目的K(ickstart)r

    “k9r”是一个专为Typesafe项目设计的工具,其全称为“K(ickstart)r”。这个工具的主要目的是为Play框架、Akka、Scala和Spark等技术栈提供快速启动的项目模板,帮助开发者快速构建新项目。 **描述详解:** 描述...

    gcchr:使用 Typesafe Akka 框架进行响应的 Spring-Boot 示例应用程序

    Spring-Boot 的示例应用程序使用 Typesafe Akka 框架进行了响应。 GCCHR 医学研究中心自动化一个医学研究中心流程自动化项目,处理患者、医生、员工、工资、财务、库存、预约安排、付款等数据... 基于最新技术的完整...

    url-builder:Kotlin Typesafe URL构建器

    网址构建器 Kotlin的直观URL构建器。 当前支持JVM和JS目标 设置 repositories { ...} 多平台项目 kotlin { sourceSets { val commonMain by getting { ... implementation( " io.github.detachhead:url-builder: $...

    config-1.2.1-API文档-中文版.zip

    标签:typesafe、config、中文文档、jar包、java; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可纵览文档内容。 人性化翻译,文档中的代码和结构保持不变,注释和说明精准翻译,请放心使用...

    MyConfig:Typesafe Config-通过示例工作

    **MyConfig: Typesafe Config 通过示例工作** 在Java开发中,配置管理是一个至关重要的环节,它确保了应用程序能够根据不同的环境和需求进行灵活调整。Typesafe Config库,由Lightbend公司(前身为Typesafe)开发,...

    typesafe-config-util:Typesafe Config Utility

    Typesafe Config Utility是一个工具,它基于Typesafe Config库进行了扩展,为Java开发者提供了一种更加便利的方式来管理和处理应用配置。Typesafe Config最初由Lightbend公司(前身为Typesafe)开发,是Java和Scala...

    ssl-config-core_2.11-0.3.7-API文档-中文版.zip

    标签:typesafe、ssl、config、core、中文文档、jar包、java; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可纵览文档内容。 人性化翻译,文档中的代码和结构保持不变,注释和说明精准翻译...

    ssl-config-core_2.11-0.3.7-API文档-中英对照版.zip

    标签:typesafe、ssl、config、core、中英对照文档、jar包、java; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可纵览文档内容。 人性化翻译,文档中的代码和结构保持不变,注释和说明精准...

    typesafeconfig-for-webapps-1.1.zip

    Typesafe Config是Lightbend公司(前身为Typesafe)推出的一款强大的配置管理工具,它为Java和Scala应用程序提供了一种类型安全的方式来读取配置信息。这个"typesafeconfig-for-webapps-1.1.zip"文件包含的是一个...

    aws-policies:Typesafe AWS策略操作

    "aws-policies:Typesafe AWS策略操作"项目可能是为了提供一种更安全、类型安全的方式来管理和构建AWS IAM(Identity and Access Management)策略。 使用TypeScript编写AWS策略可以带来诸多好处。TypeScript是...

    config-1.3.0-API文档-中文版.zip

    标签:typesafe、config、中文文档、jar包、java; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可纵览文档内容。 人性化翻译,文档中的代码和结构保持不变,注释和说明精准翻译,请放心使用...

    config4k:Typesafe Config的Kotlin包装器

    `config4k` 是一个针对 `Typesafe Config` 的 Kotlin 库,它为使用 Kotlin 进行应用程序配置提供了更方便、更直观的方式。`Typesafe Config` 原本是用 Java 编写的,广泛应用于 Scala 和 Java 项目中,它允许开发者...

    config-1.3.3-API文档-中文版.zip

    标签:typesafe、config、jar包、java、API文档、中文版; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可纵览文档内容。 人性化翻译,文档中的代码和结构保持不变,注释和说明精准翻译,请...

    config-1.3.0-API文档-中英对照版.zip

    标签:typesafe、config、中英对照文档、jar包、java; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可纵览文档内容。 人性化翻译,文档中的代码和结构保持不变,注释和说明精准翻译,请放心...

    typestyle:使CSS Typesafe:rose:

    字体样式 使CSS类型安全。 使用TypeStyle编写CSS与使用TypeScript编写JavaScript一样流畅。 js框架中有很多CSS。 这是不同的: 提供出色的TypeScript开发人员经验。 无需自定义AST转换或模块加载器支持。...

    cpp-hocon:Typesafe Config库的C ++端口

    C ++ HOCON解析器 这是TypesafeConfig库到C ++的端口。 该库为提供了C ++支持。 MMMMMMMMMMMMMMMMMMMM .====================. MMMMMMMMMMMMMMMMMMMMMM .MMMMMMMMMMMMMMMMMMMMMM. ===.7MMMIN7NMMMMMMMMM7M=MMMM,=== ...

    akka-stream_2.11-2.5.21-API文档-中文版.zip

    标签:typesafe、akka、stream、中文文档、jar包、java; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可纵览文档内容。 人性化翻译,文档中的代码和结构保持不变,注释和说明精准翻译,请...

    siesta:SQL的Typesafe API

    之所以是Typesafe,是因为查询是用强类型的Java代码编写的,而不仅仅是嵌入在字符串中。 例子 让我们看几个例子,看看它是如何工作的。 插入数据库 首先,我们将创建一个使用的表。 &lt; colum

Global site tag (gtag.js) - Google Analytics