有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java:无效的方法引用

对于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是要点。有人知道为什么这是无效的,希望是一个解决办法吗

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


共 (1) 个答案

  1. # 1 楼答案

    我猜您的构造函数需要一个Function<Object, T>或类似的值。它无法知道你打算开一个账户。解决这个问题的一种方法是使类具有两个泛型

    class MetaProperty<A, R> {
        MetaProperty(Function<A, R> getter) { /* */ }
    }
    
     public static final MetaProperty<Account, Integer> BALANCE_PROP_INVALID 
                                                        = new MetaProperty<>(Account::getBalance);