Java 8 uses generic type method references
•
Java
I have the problem of combining Java 8 method references with generic types I have simplified my problem and made it clear The following code failed:
public static void main(String[] args) { new Mapper(TestEvent::setId); } private static class Mapper<T> { private BiConsumer<TestEvent,T> setter; private Mapper(BiConsumer<TestEvent,T> setter) { this.setter = setter; } } private static class TestEvent { public void setId(Long id) { } }
But if I change the constructor call to
BiConsumer<TestEvent,Long> consumer = TestEvent::setId; new Mapper(consumer);
Everything worked. Can anyone explain why
I know that if I delete the generic type (T) and replace it with long, it won't work in solving my real problem
Solution
At present, you are trying to use the original mapper type, which will erase all kinds of things
Once you start using generic types, everything is fine - type inference can help you:
new Mapper<>(TestEvent::setId);
Add < > all these are needed for your code compilation
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码