When a class literal is passed among methods to communicate both compile-time and runtime type information.

Map<Class<T>, Object>

Class's cast method

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.

public class Class<T> {

T cast(Object obj);

}

Demo for a typesafe heterogeneous container.

import java.util.HashMap;

import java.util.Map;

/**

* @author Kaibo

*

*/

public class Favorites {

private Map<Class<?>, Object> favorites = new HashMap<Class<?>, Object>();

// Achieving runtime type safety with a dynamic cast

public <T> void putFavorite(Class<T> type, T instance) {

if (type == null)

throw new NullPointerException("Type is null");

favorites.put(type, type.cast(instance));

}

// This reestablishes this linkage between the types of key and value

public <T> T getFavorite(Class<T> type) {

return type.cast(favorites.get(type));

}

// Typesafe heterogeneous container pattern - client

public static void main(String[] args) {

Favorites f = new Favorites();

f.putFavorite(String.class, "Java");

f.putFavorite(Integer.class, 0xcafebabe);

f.putFavorite(Class.class, Favorites.class);

String favoriteString = f.getFavorite(String.class);

int favoriteInteger = f.getFavorite(Integer.class);

Class<?> favoriteClass = f.getFavorite(Class.class);

System.out.printf("%s %x %s%n", favoriteString, favoriteInteger,

favoriteClass.getName());

}

}

Limitation

  1. A malicious client could easily corrupt the type safety of a Favorites instance, simply by using a Class object in its raw form. To deal with we need to use type.cast to the input class parameter to ensure its type safety.
  2. Favorites class cannot be used on a non-reifiable type, such as List<String>. Since List<String>.class is a syntax error. The root cause for this is that List<String> and List<Integer> are the same in the run time since they are non-reifiable at run time.

Bounded type token

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

asSubclass method of Class

// Use of asSubclass to safely cast to a bounded type token

static Annotation getAnnotation(AnnotatedElement element,

String annotationTypeName) {

Class<?> annotationType= null; // Unbounded type token

try {

annotationType = Class.forName(annotationTypeName);

} catch (Exception ex) {

throw new IllegalArgumentException(ex);

}

return element.getAnnotation(

annotationType.asSubclass(Annotation.class));

}

}

Summary

The normal use of generics, exemplified by the collections APIs, restricts you to a fixed number of type parameters per container. You can get around this restriction by placing the type parameter on the key rather than the container. You can use Class objects as keys for such typesafe heterogeneous containers. A Class object used in this fashion is called a type token. You can also use a custom key type. For example, you could have a Database Rowtype representing a database row (the container), and a generic type Column<T> as its key.

Effective Java 29 Consider typesafe heterogeneous containers的更多相关文章

  1. Effective Java Index

    Hi guys, I am happy to tell you that I am moving to the open source world. And Java is the 1st langu ...

  2. 《Effective Java》读书笔记 - 5.泛型

    Chapter 5 Generics Item 23: Don't use raw types in new code 虽然你可以把一个List<String>传给一个List类型(raw ...

  3. Effective Java 目录

    <Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...

  4. 【Effective Java】阅读

    Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Obje ...

  5. Effective Java 第三版——29. 优先考虑泛型

    Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...

  6. Effective Java通俗理解(持续更新)

    这篇博客是Java经典书籍<Effective Java(第二版)>的读书笔记,此书共有78条关于编写高质量Java代码的建议,我会试着逐一对其进行更为通俗易懂地讲解,故此篇博客的更新大约 ...

  7. Effective Java 第三版——26. 不要使用原始类型

    Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...

  8. Effective Java 第三版——28. 列表优于数组

    Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...

  9. Effective Java 第三版——33. 优先考虑类型安全的异构容器

    Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...

随机推荐

  1. JS&CSS文件请求合并及压缩处理研究(一)

    在我们日常的网站开发工作中,一个页面难免会引用到各种样式及脚本文件.了解Web开发的朋友们都知道,页面引用的每一个: <link href="style.css" rel=& ...

  2. SQL SERVER2008及以上版本数据库自动备份的三种方法

    方法一:创建一个维护计划对数据库进行备份 方法二:创建一个SQL作业对数据库进行备份 方法三:创建WINDOWS任务计划对数据库进行备份 方法一与方法二其实原理基本相同,都必需开启SQL代理服务,都会 ...

  3. [Solution] NPOI操作Excel

    NPOI 是 POI 项目的 .NET 版本.POI是一个开源的Java读写Excel.WORD等微软OLE2组件文档的项目.使用 NPOI 你就可以在没有安装 Office 或者相应环境的机器上对 ...

  4. myeclipse怎么github

    myeclipse怎么github 第一步.打开myeclipse->选择项目->鼠标右键->Team->Share project,将出现如下图所示: 第二步.选择git,在 ...

  5. JAVA - package与import解析(一)

    一.为什么要引入package和import?这个问题和c++中引入命名空间是一样的,也是为了解决重名问题.java通过包机制来解决重名问题,也就相当于给重名的代码加一系列前缀,从而达到唯一标识的作用 ...

  6. 基于bootstrap的图片轮播效果展示

    <!DOCTYPE html><html lang="zh-CN"> <head> <meta charset="utf-8&q ...

  7. 【洛谷 p3382】模板-三分法(算法效率)

    题目:给出一个N次函数,保证在范围[l,r]内存在一点x,使得[l,x]上单调增,[x,r]上单调减.试求出x的值. 解法:与二分法枚举中点使区间分成2份不一样,三分法是枚举三分点,再根据题目的情况修 ...

  8. Eclipse环境下使用Maven注意事项

    在最新版本的Eclipse Java EE IDE for Web Developers中已经包含Maven 2 在File,New中可以看到Maven Project,新建, 按照步骤一路下来,要求 ...

  9. PowerShell与CMD在路径解析上的一点不同

    对于路径含有空格的文件夹,在加入PATH环境变量时,前后往往会加上引号.这种情况,CMD可以正确识别:但是Powershell却不能加上引号,否则无法定位路径. 例如,在PS中,$env:path查看 ...

  10. 【GOF23设计模式】状态模式

    来源:http://www.bjsxt.com/ 一.[GOF23设计模式]_状态模式.UML状态图.酒店系统房间状态.线程对象状态切换 package com.test.state; public ...