Java 将方法的返回值声明为公共超类型
假设我有三种类型,Java 将方法的返回值声明为公共超类型,java,generics,Java,Generics,假设我有三种类型,S,T,和U,其中S是T和U最具体的常见超类型。我可以让用户明确声明: class Foo<S, T extends S, U extends S> { public S choose(T t, U u); // chooses either t or u based on some criteria ... } class-Foo { 公共S选择(T,U);//根据某些条件选择T或U ... } 有没有办法自动推断S class Foo&l
S
,T
,和U
,其中S是T
和U
最具体的常见超类型。我可以让用户明确声明:
class Foo<S, T extends S, U extends S>
{
public S choose(T t, U u); // chooses either t or u based on some criteria
...
}
class-Foo
{
公共S选择(T,U);//根据某些条件选择T或U
...
}
有没有办法自动推断S
class Foo<T, U>
{
public ???? choose(T t, U u); // chooses either t or u based on some criteria
...
}
class-Foo
{
public???选择(T,U);//根据某些条件选择T或U
...
}
尝试使用泛型方法而不是泛型类
public class Main {
static final Random random = new Random();
public static void main(String... args) {
Bar bar = choose(new Baz(), new Qux());
}
public static <S, T extends S, U extends S> S choose(T one, U two) {
return random.nextBoolean() ? one : two;
}
interface Foo{}
interface Bar extends Foo{}
static class Baz implements Bar{}
static class Qux implements Bar{}
}
公共类主{
静态最终随机=新随机();
公共静态void main(字符串…参数){
Bar Bar=选择(新Baz(),新Qux());
}
公共静态S选择(T 1,U 2){
返回random.nextBoolean()?一:二;
}
接口Foo{}
接口栏扩展了Foo{}
静态类Baz实现Bar{}
静态类Qux实现了Bar{}
}
类似但不同于如何更好?客户机在实例化类时不必声明泛型类型(显然,静态只是为了方便;它可能是一个实例方法)。但是,这一方法的适用性非常有限。类被参数化为T
和U
可能是有原因的。方法中的参数与类的参数完全无关。一种解决方法是让choose
只返回Object
并将调用包装成S调用(Foo c,T T,U){return(S)c.choose(T,U);}
,使用(未选中但安全的)强制转换,但这也不太可能是合理的解决方案……:-/