【发布时间】:2021-04-20 23:23:52
【问题描述】:
问题陈述:我们正在构建一个以 TypeSafeMap 作为响应的库。 TypeSafeMap 是一个可以容纳任何类型对象的映射。 现在,客户端将访问 typesafemap。我们正在尝试强制执行某种程度的编译类型安全。下面是代码和更多解释。
响应结构:
public Class Response {
private TypeSafeMap t;
public TypeSafeMap getMap() { return t; }
}
//类型安全映射
public class TypeSafeMap
{
private final static Map<String, Object> map = new HashMap<>();
public static <T> T put(String key, T value) {
if (null != key) {
return (T) map.put(key, value);
}
return (T) map;
}
@SuppressWarnings("unchecked")
public static <T> T get(PartyEnums partyEnum)
{
return (T) map.get(partyEnum.PARTY.name());
}
}
//我们暴露给客户端获取属性和对应字段类型的枚举
public enum PartyEnums
{
PARTY("party", new ArrayList<Party>().getClass());
private final String name;
private final Class<?> clzz; //this is the type client should access as field type
PartyEnums(String name,Class<?> clzz)
{
this.name = name;
this.clzz=clzz;
}
public Class<?> getClzz()
{
return clzz;
}
@SuppressWarnings("unchecked")
public <T> T getInstance()
{
T ins = null;
try {
ins = (T) getClzz().newInstance();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
return ins;
}
}
//客户端调用
public class ClientCall {
Object obj = TypeSafeMap.get(PartyEnums.PARTY); //No error.
String str = TypeSafeMap.get(PartyEnums.PARTY); //No error.
But we want enforce some level of compile type safety as the field type "str" and TypeSafeMap.get() type do not match.
How can we enforce compile type safety?
List<Party> party = TypeSafeMap.get(PartyEnums.PARTY);// OK.
}
【问题讨论】:
标签: java spring-boot generics collections enums