简体   繁体   English

从Class <T>到Thing <T>的类型安全映射

[英]Type-safe mapping from Class<T> to Thing<T>

I want to make a map-kind of container that has the following interface: 我想制作一个具有以下界面的地图类容器:

public <T> Thing<T> get(Class<T> clazz);
public <T> void put(Class<T> clazz, Thing<T> thing);

The interesting point is that the T s in each Class<T> -> Thing<T> pair is the same T , but the container should be able to hold many different types of pairs. 有趣的是,每个Class<T> - > Thing<T>对中的T s是相同的T ,但容器应该能够容纳许多不同类型的对。 Initially I tried a (Hash) Map . 最初我尝试了一个(哈希) 地图 But, for instance, 但是,例如,

Map<Class<T>, Thing<T>>

is not right, because then T would be the same T for all pairs in that map. 是不对的,因为那么T也是一样T在该地图中的所有对。 Of course, 当然,

Map<Class<?>, Thing<?>>

works, but then I don't have type-safety guarantees so that when I get(String.class) , I can't be sure that I get a Thing<String> instance back. 工作,但后来我没有类型安全保证,所以当我get(String.class) ,我不能确定我得到一个Thing<String>实例。

Is there an obvious way to accomplish the kind of type safety that I'm looking for? 有没有一种明显的方法可以实现我正在寻找的那种类型的安全性?

地图本身不能保证,但如果您只通过上述方法访问它,您将获得所需的安全性。

If you want to be able to put different types shouldn't you declare two type parameters? 如果你想能够放置不同的类型,你不应该声明两个类型参数吗?

public <K, V> Thing<V> get(Class<K> clazz);
public <K, V> void put(Class<K> clazz, Thing<V> thing);

or did I misunderstand the question? 还是我误解了这个问题?

Edit: I see, well if you want o container that can hold entities of different types, there's no way you can have complete type safety, since when you declare your container you can only put one type on the container and then you may be able to put objects in, but you can't be sure what you get back. 编辑:我明白了,如果你想要一个可以容纳不同类型实体的容器,你就无法拥有完整的类型安全性,因为当你宣布你的容器时你只能在容器上放一种类型然后你就可以了放入物品,但你不能确定你得到了什么。 At best you'll end up putting in objects as Object, and then doing instanceof and casts when you get them back. 最好你最终将对象作为Object放入,然后在你取回它时进行instanceof和强制转换。 All collections have this problem. 所有收藏都有这个问题。 Imagine you have a Collection<T extends Thing> . 想象一下,你有一个Collection<T extends Thing> You may put in it Things, ChildOfThings, or GrandChildOfThings, but when you get it back, you're only guarantee is that it's a Thing, you can't tell if it's a Child or GrandChild, without actually testing it. 你可以把它放在Things,ChildOfThings或GrandChildOfThings中,但当你把它拿回来时,你只能保证这是一件事,你无法判断它是Child还是GrandChild,而不是实际测试它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM