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年出版,到现在已经将 ...
随机推荐
- SQL Server临界点游戏——为什么非聚集索引被忽略!
当我们进行SQL Server问题处理的时候,有时候会发现一个很有意思的现象:SQL Server完全忽略现有定义好的非聚集索引,直接使用表扫描来获取数据.我们来看看下面的表和索引定义: CREATE ...
- 让JS写的更接近OOP
下面这段代码就是利用JS原型对象,来实现的类的继承DEMO $ 为jquery对象 ////公共方法 // $.oop.newClass=function newClass(obj) { // fun ...
- SQL语句技巧:查询存在一个表而不在另一个表中的数据记录
方法一(仅适用单个字段)使用 not in ,容易理解,效率低 select A.ID from A where A.ID not in (select ID from B) 方法二(适用多个字段匹配 ...
- .Net魔法堂:史上最全的ActiveX开发教程——自动更新、卸载篇
一.前言 B/S模式的特点之一,客户端版本升级相对简单.快捷,适合产品的快速迭代.而ActiveX组件的自动更新同样也继承了这一优点.下面我们一起来了解吧! 二.二话不说更新ActiveX 1. 设置 ...
- JS魔法堂:精确判断IE的文档模式by特征嗅探
一.前言 苦逼的前端攻城狮都深受浏览器兼容之苦,再完成每一项功能前都要左顾右盼,生怕浏览器不支持某个API,生怕原生API内含臭虫因此判断浏览器类型和版本号成了不可绕过的一道关卡,而特征嗅探是继浏览器 ...
- DZNEmptyDataSet,优秀的空白页或者出错页封装
简介 项目主页:https://github.com/dzenbot/DZNEmptyDataSet 提示:主要用于UITableView和UICollectionView,也可以用于UIScroll ...
- 重构第14天 分离职责(Break Responsibilities)
理解:面向对象的五大特征: SOLID,其中S就是职责单一原则.分离职责指当一个类有许多职责时,将部分职责分离到独立的类中,这样也符合面向对象的五大特征之一的单一职责原则,同时也可以使代码的结构更加清 ...
- 如何快速开发树形列表和分页查询整合的WInform程序界面
我在做Winform界面的时候,一般都是统一化处理,界面顶部放置一些字段条件供查询,下面就是分页查询列表,展示相关的数据.但有时候碰到一些表字段内容分类比较多,有一些特别重要,如果放在一个树形列表来进 ...
- macbook装双系统多分区其实很简单,你只要把macbook当作一台普通pc就可以了!
macbook装双系统多分区其实很简单,你只要把macbook当作一台普通pc就可以了! 不用理会苹果官网的警告,苹果官网警告你只能用bootcamp安装且不能多分区,把人吓得不轻.其实不用过多担心, ...
- linq order by charindex 排序 按给定字符串顺序排序
//list=list.OrderBy(ee => SqlFunctions.CharIndex("书记,主任,支部委员,村委委员,系统工作人员", ee.ZhiWu)).T ...