我正在尝试实现一个方法,它返回一个类的可选:A,B,C扩展母亲.
我不知道从哪里开始.我试过这样的事
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`
Run Code Online (Sandbox Code Playgroud)
几乎就在那里,这是一个更好的版本.
private <U extends Mother> Optional<U> get(String query, Class<U> clazz) {
...
}
Run Code Online (Sandbox Code Playgroud)
有界类型参数确保只能传递Mother
(或Mother.class
自身)的子类.