当无法从静态上下文中引用非静态方法时,为什么String :: isEmpty有效?

时间:2018-10-16 05:01:23

标签: java java-8

我了解错误消息。我知道我无法在静态上下文中访问非静态方法。但是为什么我可以执行以下操作:

Predicate<String> t = String::isEmpty; // this works

何时isEmpty()是String类的非静态方法?查看以下示例类。我理解不允许TestLamba :: isEmptyTest的逻辑; 但我不明白的是为什么String:isEmpty可以打破此规则:

import java.util.function.Predicate;

public class TestLamba {

    public static void main(String... args) {

        Predicate<String> t = String::isEmpty; // this works
        Predicate<String> t2 = TestLamba::isEmptyTest; // this doesn't
    }

    public boolean isEmptyTest() {
        return true;
    }

}

这是String.isEmpty的来源。这是一种非常常见的方法,您可以看到它不是静态的:

public boolean isEmpty() {
    return this.value.length == 0;
}

1 个答案:

答案 0 :(得分:6)

isEmptyString类的功能,而isEmptyTestTestLamba类的功能。

import java.util.function.Predicate;

public class TestLamba {

    public static void main(String... args) {

        Predicate<String> t = String::isEmpty; // this works
        Predicate<TestLamba > t2 = TestLamba::isEmptyTest; // this now will work
    }

    public boolean isEmptyTest() {
        return true;
    }

}