10

I am having issues with Java 8 method reference combined with generic types. I have simplified my problem to make it clear where the problem lies. The following code fails:

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 invocation to

    BiConsumer<TestEvent, Long> consumer = TestEvent::setId;
    new Mapper(consumer);

Everything works. Can someone explain why?

I know that it works if I remove the generic type (T) and use Long instead, but that will not work when solving my real problem.

0

1 Answer 1

16

Currently you're trying to use the raw mapper type, which erases all kinds of things.

As soon as you start using the generic type, all is fine - and type inference can help you:

new Mapper<>(TestEvent::setId);

Adding <> is all that's required to make your code compile.

Sign up to request clarification or add additional context in comments.

3 Comments

Can downvoter explain what is wrong with this answer?
Thanks! Can't wait to try this out once I have access to my computer again.
Works! Marking as answered.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.