我实际上总是需要其他方法(使用 .getClass()),所以我想这两种实现都可能有用..
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); //ADDS Number -> 4
//favorites.putFavorite(Integer.class, num); //Error: no suitable method found for putFavorite(java.lang.Class<java.lang.Integer>,java.lang.Number)
favorites.putFavorite(num); //ADDS Integer -> 4
System.out.println(favorites.favorites); //{class java.lang.Integer=4, class java.lang.Number=4}
}
}