[英]Java Generic Type Erasure when using Optional
Definition in class: 课堂上的定义:
class XXX {
Map<String, Class> someMap;
public <K, V>
Optional<V> get(K key) {
return Optional.ofNullable(getNullable(key));
}
public <K, V>
V getNullable(K key) {
//someMap already holds key -> class of V
String value = DB.fetch(key);
return gson.fromJson(value, someMap.get(key.toString()));
}
}
Usage: 用法:
//xxx is an instance of XXX
Optional<ClassA> valueOpt = xxx.get(key); //this is fine
ClassA value = valueOpt.get(); //this is fine
//The intermediate valueOpt seems redundant, try to bypass it.
ClassA value = xxx.get(key).get(); //this does not work
My question: in the last line, seems the type info is deducible, why cannot it work? 我的问题:在最后一行中,似乎类型信息是可推论的,为什么它不起作用? any workaround to make it work in one line?
任何解决方法,使其在一行中工作?
Workarounds summary: 解决方法摘要:
1) xxx.get(key, ClassA.class)
1)
xxx.get(key, ClassA.class)
2) (ClassA)xxx.get(key)
2)
(ClassA)xxx.get(key)
3) xxx.<K,ClassA>get(key)
3)
xxx.<K,ClassA>get(key)
I still feel those are all workarounds because ClassA value = xxx.getNullable(key);
我仍然觉得这些都是解决方法,因为
ClassA value = xxx.getNullable(key);
can work. 能行得通。
您可以使用方法类型参数来明确表示:
ClassA value2 = xxx.<String, ClassA>get(key).get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.