创建一个类,使其接受一个Class<?>作为键,一个Set<?>作为值,向映射中添加新类型的唯一方法是通过 void addRepository(Class key)这个方法

public class Repository {
    private final Map<Class<?>, Set<?>> repo = new HashMap<>();
    private static Repository instance = null;
    private Repository() {}

    public static synchronized Repository getInstance() {
        if(instance == null) {
            instance = new Repository();
        }

        return instance;
    }
    //一个用于添加新仓库的方法
    public <T> void addRepository(Class<T> key) {
        Set<?> existing = repo.putIfAbsent(key, new HashSet<>());
        if (existing != null) {
            throw new IllegalArgumentException("Key " + key + " 已经创建");
        }
    }
	  //一个用于获取现有仓库的方法
    public <T> Set<T> getRepository(Class<T> key) {
        Set<?> subRepo = repo.get(key);
        if (subRepo == null) {
            throw new IllegalArgumentException("没找到" + key);
        }
        return (Set<T>) subRepo;
    }
}

用法示例:

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Repository repository = Repository.getInstance();
        repository.addRepository(String.class);
        repository.addRepository(Integer.class);
        Set<String> stringRepo = repository.getRepository(String.class);
        stringRepo.add("Hey");
        stringRepo.add("Jude");
        Set<Integer> intRepo = repository.getRepository(Integer.class);
        intRepo.add(1);
        intRepo.add(4);
    }
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐