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. (翻译)为你的MVC应用程序创建自定义视图引擎

    Creating your own MVC View Engine For MVC Application 原文链接:http://www.codeproject.com/Articles/29429 ...

  2. IOS开发UI基础UILabel属性

    UILabel属性 1.text:设置标签显示的文本. 2.attributedText:设置标签属性文本. Ios代码 NSString *text = @"first";  N ...

  3. Genymotion模拟器环境搭建中的各种坑,终极解决办法

    最近刚进入了一家公司,因为要做自动化测试,web端的业务需要移动端来进行配合,想了想还是利用genymotion模拟器吧:很久前装过,那也是一路坎坷啊,结果这次还是遇到坑了,搞了老半天:我希望我踩过的 ...

  4. enum to IEnumerable<T>

    想foreach一个枚举,发觉它特别复杂,因此先把枚举转换为IEnumerable接口之后,简单多了.下面是枚举(enum)转换为IEnumerable接口方法: 使用:修改这篇<程序一旦发觉写 ...

  5. Web控件文本框Reset的功能

    在前一篇中<怎样实现Web控件文本框Reset的功能>http://www.cnblogs.com/insus/p/4120889.html Insus.NET只实现了文本框的功能.单个或 ...

  6. U3D自定义Inspector项未触发保存事件的解决方案

    1.问题描述与解决方案 1.1.说明 应该只有起步做U3D编辑器插件的部分同行需要了解本文. 该问题源于在做UI插件的时候,发现Inspector面板上手动修改值后,没有触发U3D编辑器本身的修改事件 ...

  7. .NET程序的编译和运行

    程序的编译和运行,总得来说大体是:首先写好的程序是源代码,然后编译器编译为本地机器语言,最后在本地操作系统运行. 下图为传统代码编译运行过程: .NET的编译和运行过程与之类似,首先编写好的源代码,然 ...

  8. Python轻量Web框架Flask使用

    http://blog.csdn.net/jacman/article/details/49098819 目录(?)[+] Flask安装 Python开发工具EclipsePyDev准备 Flask ...

  9. 无法打开Android SDK Manager的解决办法

    不知道从什么时候开始,打开Android的SDK Manager.exe时,命令行窗口一闪就自动关掉了. 想更新一些Android的东西都更新不了. 查了一下,解决办法是: 环境变量的系统变量Path ...

  10. weblogic 12c下jxls导出excel报错Could not initialize class org.apache.poi.xssf.usermodel.XSSFVMLDrawing

    周一,开发反馈weblogic 12c下jxls导出excel报错,公司环境和UAT环境均报错,看日志如下: 2016-06-08 09:16:55,825 ERROR org.jxls.util.T ...