Effective Java 29 Consider typesafe heterogeneous containers
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
- 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.
- 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的更多相关文章
- 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 ...
- 《Effective Java》读书笔记 - 5.泛型
Chapter 5 Generics Item 23: Don't use raw types in new code 虽然你可以把一个List<String>传给一个List类型(raw ...
- Effective Java 目录
<Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...
- 【Effective Java】阅读
Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Obje ...
- Effective Java 第三版——29. 优先考虑泛型
Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...
- Effective Java通俗理解(持续更新)
这篇博客是Java经典书籍<Effective Java(第二版)>的读书笔记,此书共有78条关于编写高质量Java代码的建议,我会试着逐一对其进行更为通俗易懂地讲解,故此篇博客的更新大约 ...
- Effective Java 第三版——26. 不要使用原始类型
Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...
- Effective Java 第三版——28. 列表优于数组
Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...
- Effective Java 第三版——33. 优先考虑类型安全的异构容器
Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...
随机推荐
- Android 学习笔记之Volley(六)实现获取服务器的字符串响应...
学习内容: 1.使用StringRequest实现获取服务器的字符串响应... 前几篇一直都在对服务——响应过程的源码进行分析,解析了整个过程,那么Volley中到底实现了哪些请求才是我们在开发中 ...
- lnmp_auto:自动化安装lnmp环境脚本
朋友找我在一台机器上帮忙安装下discuz.想着搭建过好几次的lnmp了,但是还没有使用过"一键安装"的自动化脚本,去网上有搜索出来,但是运行的时候发现用root运行别人的脚本还是 ...
- 请求参数到表述层的类型转换——Struts2
一.简介 说明:HTTP 协议传输数据没有类型的概念,在服务器端是通过 request.getParameter().request.getParameterValue() 方法得到请求参数为 Str ...
- Node.js爬虫抓取数据 -- HTML 实体编码处理办法
cheerio DOM化并解析的时候 1.假如使用了 .text()方法,则一般不会有html实体编码的问题出现 2.如果使用了 .html()方法,则很多情况下(多数是非英文的时候)都会出现,这时, ...
- 关于SqlServer2012本地帮助文档安装失败问题
由于本人在前一段时间安装了SqlServer2012,安装后没有自带本地帮助文档,因为新的数据库版本微软捆绑了一个本地帮助文档查看器软件,所以在这个软件里面选择联机安装的时候,总是下载不成功,原因你们 ...
- CSS控制文本超出指定宽度显示省略号和文本不换行
一般的文字截断(适用于内联与块): .text-overflow { display:block;/*内联对象需加 */ width:31em;/* 何问起 hovertree.com */ word ...
- mongodb学习1---基本命令
0:基本命令:1,登录mongodb数据库mongo 2,查看数据库,选择数据库show dbs;use table1; 3,查看集合show collections; 4,查看集合所有数据db.集合 ...
- XLConnect:一个用R处理Excel文件的高效平台
code{white-space: pre;} pre:not([class]) { background-color: white; }if (window.hljs && docu ...
- Android 手机卫士17--缓存清理
清理单个应用缓存 通过反射调用方法 需要权限:android.permission.DELETE_CACHE_FILES. 以上权限为系统权限,手机卫士应用为用户应用,不能拿到此权限 换思路: 调用系 ...
- SwipeRefreshLayout下拉刷新
1.SwipeRefreshLayout是Google在support v4 19.1版本的library更新的一个下拉刷新组件,实现刷新效果更方便. 弊端:只有下拉 //设置刷新控件圈圈的颜色 sw ...