该表达式的目标类型必须是函数式接口 -Java 8 Functoinal Interface

The target type of this expression must be a functional interface -Java 8 Functoinal Interface

我只是对 lambdas.I 收到以下错误有一点疑问 code.If 我正在调用一个 returns 布尔值或其他类型的方法,我不知道没看到这个 issue.How 我可以解决这个问题吗?

错误:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: The method forEach(Consumer) in the type Iterable is not applicable for the arguments (( bean) -> {}) The target type of this expression must be a functional interface

at com.wipro.MethodReference.main(MethodReference.java:18)

package com.sample;

import com.student.MockClass;

import java.util.ArrayList;
import java.util.List;

public class MethodReference {
    public static void main(String[] args) {
        MockClass obj = new MockClass("JSP", 2);
        MockClass obj1 = new MockClass("Java", 8);
        List<MockClass> listofBeans = new ArrayList<MockClass>();
        listofBeans.add(obj);
        listofBeans.add(obj1);
        listofBeans.forEach(bean -> MethodReference::call);
    }

     public static void call(){
        System.out.println("Hii!!!");
    }    
}

功能接口(在本例中为 Consumer)的目的是通过流传递数据。您的方法 call() 没有多大意义,因为它不接受任何参数并且 returns 不接受任何参数。您可以这样做,但不能使用方法参考。

试试这个:

listofBeans.forEach(MethodReference::call);
public static void call(MockClass bean){...}

listofBeans.forEach(bean -> call());

JLS 描述方法引用表达式:

A method reference expression is compatible in an assignment context, invocation context, or casting context with a target type T if T is a functional interface type (§9.8) and the expression is congruent with the function type of the ground target type derived from T.

所以你必须assign/cast它到函数接口。

listofBeans.forEach(bean-> ((Runnable)MethodReference::call).run());

等同于:

listofBeans.forEach(bean-> call());