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

前端 未结 5 2047
野趣味
野趣味 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:33

    What you are using is a heterogeneous container. These can be made typesafe by using type tokens (as you already do) and Class.cast() with the correct application logic: So there is an unchecked suppressWarning within Class.cast(), but the application logic guarantees correctness.

    I advise you read Josh Bloch's Effective Java Item 29: Consider typesafe heterogeneous containers. His example is:

    // Typesafe heterogeneous container pattern - implementation
    public class Favorites {
      private Map, Object> favorites =
        new HashMap, Object>();
    
      public  void putFavorite(Class type, T instance) {
        if (type == null)
          throw new NullPointerException("Type is null");
        favorites.put(type, instance);
      }
    
      public  T getFavorite(Class type) {
        return type.cast(favorites.get(type));
      }
    }
    

    I only see a possibility for memory leakage if you hold arbitrarily many different types you actually no longer need.

提交回复
热议问题