Java map, key = class, value = instance of that class

前端 未结 5 2043
野趣味
野趣味 2020-12-08 15:11

I\'m not sure what I want to do is possible, but if it is, I want to find out how. Basically, I want to create a Map where the key is a class (java.lang.Class),

5条回答
  •  眼角桃花
    2020-12-08 15:49

    This isn't possible due to type erasure.

    However, you could subclass HashMap and write some logic into the put method which will do this for you:

    public void put(K key, V value) {
    
        if  ( // value is an instance of key using .getClass()) { 
            super.put(key, value)
        }
        throw new Exception();
    }
    

    (Code for illustrative purposes only)

提交回复
热议问题