Java:神秘的无效方法参考

Java: Mystery Invalid Method Reference

同时使用 JDK 1.8.0_181 和 JDK 10.0.2 我收到此编译错误:

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

对于这个变量声明:

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

但是这个编译和运行都很好:

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

Here 是要点。有谁知道为什么这是无效的并且希望是一种解决方法?

仅供参考,我对反射不感兴趣。

我的猜测是您的构造函数需要一个 Function<Object, T> 或类似的。它无法知道您想要一个帐户。解决此问题的一种方法是使 class 具有两个泛型。

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

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