아이템33 타입 안전 이종 컨테이너를 고려하라
Effective Java 3e 아이템 33를 요약한 내용 입니다.
더 유연한 수단이 필요할 때도 종종 있다.
다행히 쉬운 해법이 있다.
public class Favorite {
private Map<Class<?>, Object> favorites = new HashMap<>();
public <T> void putFavorite(Class<T> type, T instance) {
favorites.put(Objects.requireNonNull(type), type.cast(instance));
}
public <T> T getFavorite(Class<T> type) {
return type.cast(favorites.get(type));
}
}public static void main(String[] args) {
Favorites f = new Favorites();
f.putFavorite(String.class, "Java");
f.putFavorite(Integer.class, 0xcafebabe);
f.putFavorite(Class.class, Favorites.class);
String favoriteString = f.getFavorite(String.class);
int favoriteInteger = f.getFavorite(Integer.class);
Class<?> favoriteClass = f.getFavorite(Class.class);
System.out.printf("%s %x %s\\n", favoriteString, favoriteInteger, favoriteClass.getName());
}Favorite 클래스에는 알아두어야 할 제약이 두 가지 있다.
Favorite 클래스에는 알아두어야 할 제약이 두 가지 있다.정리
Last updated