我想要编译这样的东西:
public class RepositoryService {
public Map<Class<? extends T>, List<T>> repository;
public RepositoryService() {
repository = new HashMap<>(); // doesn't matter which implementation
repository.put(Integer.class, Arrays.asList(1, 2, 3));
repository.put(String.class, Arrays.asList("A", "B", "C"));
}
public List<T> get(Class clazz) {
return repository.get(clazz);
}
}
这可能吗?
最佳答案
您可以通过 RepositoryService
上确保类型匹配的实例方法仅添加到映射来做得更好。
import static java.util.Arrays.asList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class RepositoryService {
private Map<Class<?>, List<?>> repository = new HashMap<>();
@SuppressWarnings("unchecked")
public <T> List<T> put(Class<T> key, List<T> instances) {
return (List<T>) repository.put(key, instances);
}
@SuppressWarnings("unchecked")
public <T> List<T> get(Class<T> key) {
return (List<T>) repository.get(key);
}
public static void main(String[] args) {
RepositoryService repositoryService = new RepositoryService();
repositoryService.put(Integer.class, asList(1, 2, 3));
repositoryService.put(String.class, asList("A", "B", "C"));
repositoryService.put(String.class, asList(1, 2, 3)); // doesn't compile
List<Integer> integers = repositoryService.get(Integer.class);
List<String> strings = repositoryService.get(String.class);
List<Double> doubles = repositoryService.get(String.class); // doesn't compile
System.out.println(integers);
System.out.println(strings);
}
}
关于java - 一个类可以有一个映射属性,其中 Class 对象作为键,作为该类对象列表的值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32239160/