Java – why is string:: isempty valid when a static context cannot reference a non static method?
•
Java
I understand the error message I know I cannot access non - static methods in a static context But why can I do the following:
Predicate<String> t = String::isEmpty; // this works
When isempty() is a non static method of string class? View the following sample classes I understand the logic that testlamba:: isemptytest is not allowed; But I don't understand why string: isempty can break this rule:
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;
}
}
This is string Isempty source code This is a very common method. You can see that it is not static:
public boolean isEmpty() {
return this.value.length == 0;
}
Solution
Isempty is a function of string class and isemptytest is a function of testlamba class
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;
}
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
