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

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

问题描述

我试图按照Joshua Bloch的有效Java的类型安全异构容器模式来创建一个容器对象( MyGeneric< T> ),其中 Class< ; T> 作为关键字。

  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));




$ b $ p
$ b

问题在于getFromContainer我必须执行一个未选中投。在Josh Bloch的容器中,他执行了一个安全的演员制作 - 但在我的情况下,我无法看到这种可能性。



有没有人有任何想法? / p>

干杯,
昵称。

解决方案

,使用 Class.cast() - 它被实现为 return(T)obj ,这是一个未经检查的转换。从编译器警告未经检查的转换被转移到预编译的lib的意义上说,它是作弊的。转换的类型安全性不受编译器的保护,而是通过应用逻辑。



您不应该担心未经检查的强制转换。有不能用语言表达的类型关系,但哪些程序员知道是真实的。因此,只是推翻编译器,告诉它演员是安全的。



更正

我对未经检查的投射的理解是不正确的。



Class.cast()不包含unchecked cast。演员在检查后完成,如果演员在运行时到达演员,则保证成功。

  T cast(Object obj)
如果obj是这个类的实例//检查
return( T)OBJ; // cast
else
抛出新ClassCastException


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));
    }
  }

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.

Does any one have any ideas?

Cheers, Nick.

解决方案

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.

Correction

My understanding about "unchecked cast" was incorrect.

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天全站免登陆