Effective Java 29 Consider typesafe heterogeneous containers

时间:2022-12-29 22:26:05

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&period;泛型

    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&period; 优先考虑泛型

    Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...

  6. Effective Java通俗理解(持续更新)

    这篇博客是Java经典书籍<Effective Java(第二版)>的读书笔记,此书共有78条关于编写高质量Java代码的建议,我会试着逐一对其进行更为通俗易懂地讲解,故此篇博客的更新大约 ...

  7. Effective Java 第三版——26&period; 不要使用原始类型

    Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...

  8. Effective Java 第三版——28&period; 列表优于数组

    Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...

  9. Effective Java 第三版——33&period; 优先考虑类型安全的异构容器

    Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...

随机推荐

  1. 实现3D旋转效果的方法

    Android中有一种旋转效果,是将一个图片进行360度的旋转. Matrix的作用是对平面上的View进行缩放.平移.旋转,每一种操作都配了setXXX.preXXX.postXXX三个函数. Ca ...

  2. 制作Linux下程序安装包——使用脚本打包bin、run等安装包

    制作简单的安装包的时候可以简单的用cat命令连接两个文件,然后头部是脚本文件,执行的时候把下面的文件分解出来就行了.一般这个后部分的文件是个压缩 包,那样,就能够打包很多文件了,在脚本中解压出来即可. ...

  3. PHP中的赋值-引用or传值?

    直接上代码: <?php $num1 = 1; $num2 = $num1; $num1 = 2; echo $num2 . "\n"; $arr1 = array(1, 2 ...

  4. Android studio导出AAR包问题整理。

    最近因为项目需求开始整理一个SDK 以AAR的方式提供出去.在整理的过程中遇到了很多坑. 以下是一些总结希望能帮助遇到同样问题的人. 1.怎么导出AAR,这种文章太多了,我贴一个大家可以做参考. ht ...

  5. LeetCode算法题-Quad Tree Intersection(Java实现)

    这是悦乐书的第260次更新,第273篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第127题(顺位题号是558).四叉树是树数据,其中每个内部节点恰好有四个子节点:top ...

  6. Python2基础

    1.python 3.python函数 python的函数定义: 以def关键字定义一个函数: 参数放在小括号里面: 必须有return语句: 关键字参数: 即调用函数时传参顺序可以人为指定 默认参数 ...

  7. The Cat in the Hat POJ - 1289

    题意:给你来两个数A,B  .其中A=(n+1)k, B=nk    输出:(nk-1)/(n-1) 和  ∏ (n+1)k-i ni 思路:关键就是怎么求n和k.本来想这n一定是几个质因数的乘积,那 ...

  8. OSGeo&period;OGR&period;Geometry

    #region 程序集 ogr_csharp.dll, v2.0.50727 // D:\KM行业需求\C++\gdal17_cSharp\ogr_csharp.dll #endregion usin ...

  9. android:活动的最佳实践

    2.6.1    知晓当前是在哪一个活动 这个技巧将教会你,如何根据程序当前的界面就能判断出这是哪一个活动.可能你会觉 得挺纳闷的,我自己写的代码怎么会不知道这是哪一个活动呢?很不幸的是,在你真正进入 ...

  10. laravel通过Eloquent ORM实现CURD

    //Eloquent ORM public function orm1() { //all(); 返回所有数据: /*$students=Student::all(); dd($students);* ...