[英]Inferring generics of an Optional in Java8
I'm trying to implement a method which returns an Optional of either classes: A,B,C extends Mother. 我正在尝试实现一个返回任一类的Optional的方法:A,B,C扩展Mother。
I have no idea where to start. 我不知道从哪里开始。 I tried something like this
我尝试过这样的事情
private Optional<U> get(String query,U u){
}
A = c.get("Looking for an A",A.class)
B = c.get("Looking for an B",B.class)
C = c.get("Looking for an C",C.class)
C = c.get("Looking for an k",k.class) // Exception, K doesn't extend `Mother`
Almost there, here's a better version. 几乎在那里,这是一个更好的版本。
private <U extends Mother> Optional<U> get(String query, Class<U> clazz) {
...
}
The bounded type parameter makes sure can only pass a subclass of Mother
(or Mother.class
itself). bounded类型参数可确保只能传递
Mother
的子类(或Mother.class
本身)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.