在Java中是否有一种方法可以使用映射,其中值的类型参数与键的类型参数相关联?我想写的内容如下:
public class Foo {
// This declaration won't compile - what should it be?
private static Map<Class<T>, T> defaultValues;
// These two methods are just fine
public static <T> void setDefaultValue(Class<T> clazz, T value) {
defaultValues.put(clazz, value);
}
public static <T> T getDefaultValue(Class<T> clazz) {
return defaultValues.get(clazz);
}
}
Run Code Online (Sandbox Code Playgroud)
也就是说,只要值的类型与Class对象的类型匹配,我就可以对Class对象存储任何默认值.我不明白为什么不允许这样做,因为我可以确保在设置/获取类型正确的值时.
编辑:感谢cletus的回答.我实际上并不需要地图本身的类型参数,因为我可以确保获取/设置值的方法的一致性,即使它意味着使用一些稍微丑陋的演员表.
假设我有以下表结构:
create table PEOPLE (
ID integer not null primary key,
NAME varchar(100) not null
);
create table CHILDREN (
ID integer not null primary key,
PARENT_ID_1 integer not null references PERSON (id),
PARENT_ID_2 integer not null references PERSON (id)
);
Run Code Online (Sandbox Code Playgroud)
我想生成每个父母的姓名列表。在光滑的我可以写这样的东西:
for {
parent <- people
child <- children if {
parent.id === child.parent_id_1 ||
parent.id === child.parent_id_2
}
} yield {
parent.name
}
Run Code Online (Sandbox Code Playgroud)
这会生成预期的 SQL:
select p.name
from people p, children c
where p.id = c.parent_id_1 or p.id …Run Code Online (Sandbox Code Playgroud)