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



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

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;
}

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; //Now this will work
}
public boolean isEmptyTest() {
return true;
}
}

最新更新