TypeMap in Java

I want to implement such a card,

Map<Class<T>, T> m;

in which I can get a generic object of type T defined by class T.

I know that you can tell, you can wrap Map<String, Object> and use casting to archive this.

I know it.

But imagine a map Map<Class<T>, Collection<T>> , in which the value is a very large collection.

I do not want to cross the collection and throw every object, since the collection is too large.

So? what should I do?

+4
source share
3 answers

I do not want to cross the collection and throw every object, since the collection is too large.

I would not worry about it because

  • you do not need to do this
  • generics is a compile-time check, so casting to a generic type does nothing at runtime.

eg. If T extends Object other than Object to T does nothing. Similarly, dropping Collection to Collection<T> does nothing at runtime.

But imagine a map Map <Class <T>, Collection <T →, in which the value is a very large collection.

If you imagine that this will do something, casting is not the answer. You may need to convert the contents of the collection, but this is completely different in Java.

+1
source

Guava has something similar, it is called ClassToInstanceMap .

You can read about this in the highlighted Wiki section .

But apparently you need a ClassToInstanceMultimap . Not yet, but you can submit a function request.

+4
source

Note that since Java uses type erasure, the implementation is actually of type

 Map<?, ?> = Map<Object, Object> 

You can trivially write a secure access method that gives you the necessary security by type and, for example, performs an instanceOf check:

 public class InstanceMap extends HashMap<Class<?>, Object> { public <T> T getInstance(Class<T> cls) { Object o = super.get(cls); if (o != null && cls.isInstance(o)) { return (T) o; } else { return null; } } public <T> void putInstance(Class<T> cls, T value) { super.put(cls, value); } @Deprecated public Object get(Object key) { return super.get(key); } } 

This will work just fine if you don't start using types that are universal in themselves. Class<? super T> Class<? super T> will help a little. But overall, it basically gives you a false sense of type safety. Such a card does not give you the reliable security you are used to. In the end, it's a little more than casting.

I used these cards before, but after using them for 1-2 years, I eventually pretty much removed them from my code during the cleanup phase. They were hacked and did not give me as many advantages as I expected from them.

0
source

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


All Articles