键入安全的异构容器模式以存储项目列表 [英] Type safe heterogeneous container pattern to store lists of items

查看:102
本文介绍了键入安全的异构容器模式以存储项目列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图实现一个类型安全的异构容器来存储异构对象的列表。



我已经看到了几种类型安全的异构容器模式( 链接),但它们都存储单个对象的类型。



我已尝试实现如下:

  public class EntityOrganizer {

private Map< Class<?>,List< Object>> entityMap = new HashMap< Class<?>,List< Object>>();

public< T>列表与LT; T> getEntities(Class< T> clazz){
return entityMap.containsKey(clazz)? entityMap.get(clazz):Collections.EMPTY_LIST;
}

私人< T> void addEntity(Class< T> clazz,T entity){
列表< T> entityList =(List< T>)entityMap.get(clazz);
if(entityList == null){
entityList = new ArrayList< T>();
entityMap.put(clazz,(List< Object>)entityList);
}
entityList.add(entity);
}
}

但是问题是这个代码充满了未经检查的转换。有人可以帮助实现这个更好的方法吗?



非常感谢

解决方案

问题是什么是unchecked cast?



有时,cast可以很安全,不幸的是,证明超出了javac的能力,这仅仅限制了静态分析在规格但是程序员比javac更聪明。



在这种情况下,我认为这些是检查的转换,并且非常适合禁止警告。



请参阅其他两个相关示例:



用Java存储通用类型对象的异构容器



Typesable forName类加载


I'm trying to implement a type-safe heterogeneous container to store lists of heterogeneous objects.

I have seen several exameples of type-safe heterogeneous container pattern (link) but all of them store a single object of a type.

I have tryed to implement it as follows:

public class EntityOrganizer {  

    private Map<Class<?>, List<Object>> entityMap = new HashMap<Class<?>, List<Object>>();

    public <T> List<T> getEntities(Class<T> clazz) {
        return entityMap.containsKey(clazz) ? entityMap.get(clazz) : Collections.EMPTY_LIST;
    }

    private <T> void addEntity(Class<T> clazz, T entity) {
        List<T> entityList = (List<T>) entityMap.get(clazz);
        if(entityList == null) {
            entityList = new ArrayList<T>();
            entityMap.put(clazz, (List<Object>) entityList);
        }
        entityList.add(entity);
    }   
}

But the problem is this code is full of unchecked casts. Can someone help with a better way of implementing this?

Many thanks

解决方案

The question is, what is "unchecked cast"?

Sometimes casts are provably safe, unfortunately the proof is beyond javac's capability, which does only limited static analysis enumerated in the spec. But the programmer is smarter than javac.

In this case, I argue that these are "checked casts", and it's very appropriate to suppress the warning.

See 2 other related examples:

Heterogeneous container to store genericly typed objects in Java

Typesafe forName class loading

这篇关于键入安全的异构容器模式以存储项目列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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