加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 当静态上下文无法引用非静态方法时,为什么String :: isE

发布时间:2020-12-15 08:27:40 所属栏目:Java 来源:网络整理
导读:我理解错误信息.我知道我无法在静态上下文中访问非静态方法.但为什么我可以做到以下几点: PredicateString t = String::isEmpty; // this works 当isEmpty()是String类的非静态方法时?查看以下示例类.我理解不允许TestLamba :: isEmptyTest的逻辑;但我不明
我理解错误信息.我知道我无法在静态上下文中访问非静态方法.但为什么我可以做到以下几点:

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

解决方法

isEmpty是String Class的函数,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;
    }

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读