在 Java 8 中使用方法引用时出现编译错误

Compilation error while using Method reference in Java 8

我不明白下面程序编译错误的原因。我哪里错了?我想使用方法参考将字符串的值打印为输出。

public class ConsumerDemo{
    public static void main(String[] args) {
        test("hello", (str)-> str::toUpperCase);
    }

    public static void test(String str, Consumer<String> consumer) {
        consumer.accept(str);

    }
 }
test("hello", String::toUpperCase)

应该是正确的语法。

为了打印输入的大写,可以使用:

String str = "hello"; // any input value
test(str.toUpperCase(), System.out::println);

您不能这样组合 lambda 语法和方法引用语法。

您正在寻找:

test("hello", String::toUpperCase);

或:

test("hello", s -> s.toUpperCase());

但这意味着 String::toUpperCase/s -> s.toUpperCase() 的结果将被忽略 因此 ,您需要执行一些更有用的操作。例如:

test("hello", s -> System.out.println(s.toUpperCase()));