我了解错误消息。我知道我无法在静态上下文中访问非静态方法。但是为什么我可以执行以下操作:
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;
}
答案 0 :(得分:6)
isEmpty
是String
类的功能,而isEmptyTest
是TestLamba
类的功能。
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;
}
}