简体   繁体   中英

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. 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. 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.

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. All collections have this problem. Imagine you have a 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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