I really need a different approach (with .getClass ()), so I assume that both implementations may be useful.
class Favorites { private Map<Class<?>, Object> favorites = new HashMap<>(); public <T> void putFavorite(Class<T> type, T instance) { favorites.put(Objects.requireNonNull(type), instance); } public <T> void putFavorite(T instance) { favorites.put(instance.getClass(), instance); } public <T> T getFavorite(Class<T> type) { return type.cast(favorites.get(type)); } public static void main(String[] args) { Favorites favorites = new Favorites(); Number num = new Integer(4); favorites.putFavorite(Number.class, num);
source share