Jason
Jason

Reputation: 2609

Java: Mystery Invalid Method Reference

With both JDK 1.8.0_181 and JDK 10.0.2 I receive this compilation error:

test\Account.java:[13,88] error: incompatible types: invalid method reference

For this variable declaration:

public final MetaProperty<Integer> BALANCE_PROP_INVALID = new MetaProperty<Integer>(Account::getBalance);

But this one both compiles and runs just fine:

public final MetaProperty<Integer> BALANCE_PROP_VALID = new MetaProperty<>(account -> ((Account) account).getBalance());

Here is the gist. Does anyone know why that's invalid and hopefully a workaround?

FYI I am not interested in reflection.

Upvotes: 1

Views: 1392

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533880

My guess is that your constructor expects a Function<Object, T> or similar. It has no way of knowing you intended an Account. One way around this is to make the class have two generics.

class MetaProperty<A, R> {
    MetaProperty(Function<A, R> getter) { /* */ }
}

 public static final MetaProperty<Account, Integer> BALANCE_PROP_INVALID 
                                                    = new MetaProperty<>(Account::getBalance);

Upvotes: 2

Related Questions