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年出版,到现在已经将 ...
随机推荐
- 开放产品开发(OPD):产品负责人的工作原则和方法
月26日我将在2014 WOT全球软件技术峰会做相关的一个主题演讲[产品负责人的工作原则和方法],个原则和相应的一些方法. 以下是本次分享内容: 完整版如下,如果你喜欢想下载的话,点击 http:// ...
- 第一次接触终极事务处理——Hekaton
在这篇文章里,我想给出如何与终极事务处理(Extreme Transaction Processing (XTP) )的第一次接触,即大家熟知的Hakaton.如果你想对XTP有个很好的概况认识,我推 ...
- EF错误记录
纯属个人记录错误使用: 1.EntityType“area”未定义键.请为该 EntityType 定义键. 产生原因: 1.命名空间引用错误,可能命名重复导致引用错误 2.实体类无法识别主键或者未设 ...
- Swift使用FMDB操作SQLite
SQLite大家都懂的.本地数据库,在移动设备上使用广泛.IOS平台上自然也少不了它.最近自己折腾一个小App的时候需要使用sqlite本地数据库,上Github搜了下IOS下对SQLite的三方封装 ...
- LeetCode - 31. Next Permutation
31. Next Permutation Problem's Link ---------------------------------------------------------------- ...
- (Python学习4)List对象
1.PyListObject对象 typedef struct { PyObject_VAR_HEAD PyObject **ob_item; Py_ssize_t allocated; } PyLi ...
- Java的final关键字详解
Java中的final关键字非常重要,它可以应用于类.方法以及变量.这篇文章中我将带你看看什么是final关键字?将变量,方法和类声明为final代表了什么?使用final的好处是什么?最后也有一些使 ...
- mvc、mvp、mvvm使用关系总结
MVC MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,一种软件设计典范,用一种业务逻辑.数据.界面显示分离的方法 ...
- 进入IT企业必读的200个.NET面试题
点击打开链接 点击打开链接 版权声明:本文为博主原创文章,未经博主允许不得转载.
- 第一个app.总结
前记: 最近想整点外快,但是又没啥子技术,唉,学了一下android,想写点游戏啥的,,唉,可惜,美工,UI始终不行,代码也勉勉强强... 不过总的来说也是收获参半吧,也是有一些新的知识学到了嘛,至少 ...