在 Java 中存储通用类型对象的异构容器 [英] Heterogeneous container to store genericly typed objects in Java

查看:27
本文介绍了在 Java 中存储通用类型对象的异构容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遵循 Effective Java 中 Joshua Bloch 的类型安全异构容器模式来创建一个对象容器 (MyGeneric),其中 Class 作为键.

I am trying to follow Joshua Bloch's typesafe hetereogeneous container pattern from Effective Java to create a container of objects (MyGeneric<T>) with Class<T> as a key.

  public class MyClass {

    private Map<Class<?>, MyGeneric<?>> myContainer =
      new HashMap<Class<?>, MyGeneric<?>>();

    public <T> void addToContainer(Class<T> class, MyGeneric<T> thing) {
      myContainer.put(class, thing);
    }

    public <T> MyGeneric<T> getFromContainer(Class<T> class) {
      return (MyGeneric<T>)(myContainer.get(klass));
    }
  }

问题在于 getFromContainer 我必须执行未经检查的强制转换.在 Josh Bloch 的容器中,他执行了安全转换 - 但就我而言,我看不出这是如何实现的.

The problem is in getFromContainer I have to perform a unchecked cast. In Josh Bloch's container, he performs a safe cast - but in my case I can't see a way how this is possible.

有人有什么想法吗?

干杯,尼克.

推荐答案

在 Bloch 的版本中,使用了 Class.cast() - 实现为 return (T) obj代码>,一个未经检查的演员.从某种意义上说,关于未经检查的强制转换的编译器警告已移至预编译库,这是一种欺骗.强制转换的类型安全不是由编译器保护的,而是由应用程序逻辑保护的.

In Bloch's version, Class.cast() is used - which is implemented as return (T) obj, an unchecked cast. It's cheating in the sense that the compiler warning about unchecked cast is moved to a precompiled lib. The type safety of the cast is not guarded by compiler, but by app logic.

您也不应该担心未经检查的强制转换.有些类型关系无法用语言表达,但程序员知道它们是正确的.所以只需否决编译器,告诉它转换是安全的.

You shouldn't worry about unchecked cast either. There are type relations that cannot be expressed in the language, but which programmers know to be true. So just overrule the compiler, tell it the cast is safe.

更正

我对unchecked cast"的理解是错误的.

My understanding about "unchecked cast" was incorrect.

Class.cast() 不包含未经检查的强制转换".转换是在检查"之后完成的,如果在运行时达到转换,则保证成功.

Class.cast() does not contain "unchecked cast". The cast is done after "checking", if the cast is reached at runtime, it's guaranteed to succeed.

T cast(Object obj)
    if obj is instance of this class   // check
        return (T)obj;                 // cast 
    else
        throw new ClassCastException

这篇关于在 Java 中存储通用类型对象的异构容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆