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. 【Spark】---- Spark 硬件配置

    存储系统 Spark任务需要从一些外部的存储系统加载数据(如:HDFS 或者 HBase),重要的是存储系统要接近Spark系统,我们有如下推荐:   (1)如果可能,运行Spark在相同的HDFS节 ...

  2. [Test] 单元测试艺术(2) 打破依赖,使用模拟对象,桩对象,隔离框架

    在上节中,完成了第一个单元测试,研究了各种特性,在本节,将介绍一些更实际的例子.SUT依赖于一个不可操控的对象,最常见的例子是文件系统,线程,内存和时间等. 本系列将分成3节: 单元测试基础知识 打破 ...

  3. Github教程(1)

    Git基本命令 git diff:查看工作树,暂存区,最新提交之间的差别 举例: 在README.MD中增加一行 ## This is the subtitle 执行git diff 命令,查看当前工 ...

  4. Asp.net生成静态网页的实现代码

    现在做程序都要将动态的页面转换成静态页面,今天教大家在ASP.NET 中实现静态页面的生成方法. using System;  using System.Data;  using System.Con ...

  5. 小巧方便的MVC后端验证码,供大家学习借鉴

    调用: public ActionResult Vcode()//验证码 { string code = ValidateCode.CreateRandomCode(4); ValidateCode. ...

  6. 关于WPF绘图中的path.data在后台重新赋值的语法

    //XAML语法 <Path Name="path_M" Fill="LawnGreen" Data="M 0 0 L 100 0 L 100 ...

  7. Qt 框架 开发HTTP 服务器 开发记录

    最近需求需要开发一款 HTTP ,然后由于先前接触过Qt,就直接用Qt写HTTP服务器了,也是为了当作练手,要不然是直接上HTTP框架的. 后端用C++ Qt框架 前端为了练手 当然是纯生的 js h ...

  8. Mongoose 框架初学使用记录

    嘛.... 最近由于需要使用HTTP服务端,原先是使用的Qt框架实现的HTTP服务端,然后发现有些缺陷导致我不得不放弃这个框架,也不是完全放弃,只是HTTP服务端这里不再使用Qt,用Qt做高并发真的有 ...

  9. 泛函编程(8)-数据结构-Tree

    上节介绍了泛函数据结构List及相关的泛函编程函数设计使用,还附带了少许多态类型(Polymorphic Type)及变形(Type Variance)的介绍.有关Polymorphism的详细介绍会 ...

  10. js 自带的 reduce() 方法

    1.方法说明 , Array的reduce()把一个函数作用在这个Array的[x1, x2, x3...]上,这个函数必须接收两个参数,reduce()把结果继续和序列的下一个元素做累积计算,其效果 ...