Type-safe mapping from class <T> to Thing <T>

I want to create a map type container that has the following interface:

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

An interesting point is that T in each Class<T> β†’ Thing<T> pair is the same T , but the container should be able to store many different types of pairs. First I tried the (Hash) Map . But for example

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

incorrect because then T will be the same T for all pairs on this map. Of course,

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

works, but then I don’t have type security guarantees, so when I get(String.class) , I cannot be sure that I will return to the Thing<String> instance.

Is there an obvious way to implement the type safety type I'm looking for?

+4
source share
2 answers

The card itself does not guarantee this, but if you access it only using the above methods, you will have the necessary security.

+5
source

If you want to be able to set different types, should you not specify 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 an o container that can contain objects of different types, then you cannot have complete type safety, because when you declare your container, you can only put one type in the container, and then you can be able to place objects, but you cannot be sure that you will return. At best, you end up putting objects in Object, and then doing instanceof and throwing when you return them. All collections have this problem. Imagine you have Collection<T extends Thing> . You can put things into it, ChildOfThings or GrandChildOfThings, but when you return them, you only guarantee that this is Thing, you cannot say whether it is Child or GrandChild without testing it.

+2
source

Source: https://habr.com/ru/post/1312282/


All Articles