我有一个泛型类型参数的类Foo
static class Foo<T> {
T get() {return null;}
void set(T t) {}
}
我希望定义一个java.util.function.Consumer的实例,它适用于任何Foo而不考虑其泛型类型参数。该Consumer将简单地调用Foo实例的set方法,并传入由get方法返回的值。我决定使用Lambda来实现此Consumer:
Consumer<Foo> compilesButWithWarnings = foo -> foo.set(foo.get());
很不幸,我在这个实现过程中收到了警告。 警告是:
The method set(Object) belongs to the raw type Foo.
References to generic type Foo<T> should be parameterized.
如果我将我的lambda写成以下形式:
Consumer<Foo<?>> compileError = foo -> foo.set(foo.get());
代码将不再编译,出现以下错误:
The method set(capture#1-of ?) in the type Foo<capture#1-of ?> is not
applicable for the arguments (capture#2-of ?)
我能提供的一个没有警告的解决方案是这样的:
Consumer<Foo<?>> worksButRequiresStaticMethod = Test::setFoo;
static <ANY> void setFoo(Foo<ANY> foo) {
foo.set(foo.get());
}
现在这样写虽然可以,但有点啰嗦。如果可能的话,我想知道是否有更好的方法来编写此代码,既不会出现警告,也不需要更改Foo。
非常感谢。