存放混合类型对象的JAVA容器

来源:互联网 发布:cnc雕刻机编程软件 编辑:程序博客网 时间:2024/04/29 07:34
import java.util.*;

public class Favorites {
    // Typesafe heterogeneous container pattern - implementation
    private Map<Class<?>, Object> favorites =
        new HashMap<Class<?>, Object>();

    public <T> void putFavorite(Class<T> type, T instance) {
        if (type == null)
            throw new NullPointerException("Type is null");
        favorites.put(type, instance);
    }

    public <T> T getFavorite(Class<T> type) {
        return type.cast(favorites.get(type));
    }


    // Typesafe heterogeneous container pattern - client
    public static void main(String[] args) {
   
        Favorites favorites = new Favorites();
        favorites.putFavorite(String.class, "StringResult");
        favorites.putFavorite(Integer.class, 12);
        favorites.putFavorite(Boolean.class, false);
        System.out.println("results are: "
                + favorites.getFavorite(String.class)
                + favorites.getFavorite(Integer.class)
                + favorites.getFavorite(Boolean.class));
    }
}