I have a class Foo with a generic type parameter
static class Foo<T> {
T get() {return null;}
void set(T t) {}
}
I want to define an instance of java.util.function.Consumer that works for ANY Foo regardless of its generic type argument. The consumer will simply call the set method on the Foo instance and pass in the value returned by the get method. I decided to use a Lambda to implement the consumer:
Consumer<Foo> compilesButWithWarnings = foo -> foo.set(foo.get());
Unfortunately I get warnings with this implementation. The warning is:
The method set(Object) belongs to the raw type Foo.
References to generic type Foo<T> should be parameterized.
If I attempt to write my lambda as:
Consumer<Foo<?>> compileError = foo -> foo.set(foo.get());
the code would no longer compile giving me the error:
The method set(capture#1-of ?) in the type Foo<capture#1-of ?> is not
applicable for the arguments (capture#2-of ?)
The one solution I could come up with which compiles without warnings is this:
Consumer<Foo<?>> worksButRequiresStaticMethod = Test::setFoo;
static <ANY> void setFoo(Foo<ANY> foo) {
foo.set(foo.get());
}
which is okay for now but a little verbose. If at all possible I would like to know if there is a better way to write this code without warnings and without changing Foo.
Thank you very much.
Cant define an instance that works with any generic type. The generic type must be known for that particular instance and is part of its statically typed signature by the compiler.
This will work:
Consumer<Foo<Object>> c = (Foo<Object> o) -> o.set(o.get());
That is an instance for that particular generic parameter value (Object).
You need another “instance” for every separate type.
Makes sense?
It is like asking for a variable that is of any type.
A variable only has one type. Known at compile time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With