java - 为什么 eclipse 告诉我静态方法引用 ClassName::staticMethod 应该为 "accessed in a static way"?

标签 java lambda static-methods

我正在阅读Java 8 Method Reference: How to Use it并希望以其他方式重用 TriFunction:

    public class Numbers {

        public static void main(String[] args) throws Exception {
            TriFunction<Numbers, String, String, Integer> function = (s,  arg1,  arg2 ) -> Numbers.doSum(arg1, arg2);
            System.out.println(function.apply(new Numbers(), "1", "2"));

            //error, not warning: The method doSum(String, String) from the type Numbers should be accessed in a static way
            TriFunction<Numbers, String, String, Integer> mRef = Numbers::doSum;   
            System.out.println(mRef.apply(new Numbers(), "3", "4"));
        }

        static Integer doSum(String s1, String s2) {
            return Integer.parseInt(s1) + Integer.parseInt(s2);
        }
    } 

    interface TriFunction<T, U, V, R> {
        R apply(T t, U u, V v);
    }

我知道静态方法应该以静态方式访问。但我认为我并没有违反 Numbers::doSum 的规则。那么原因是什么呢?

最佳答案

Numbers::doSum ,当应用于TriFunction<Numbers, String, String, Integer>时,翻译为(n, s1, s2) -> n.doSum(s1, s2) ,这意味着您正在 Numbers 的实例上调用静态方法。要么将其设为实例方法,要么使用 BiFunction这并不期望 Numbers实例。

关于java - 为什么 eclipse 告诉我静态方法引用 ClassName::staticMethod 应该为 "accessed in a static way"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48778996/

相关文章:

java - 不同级别的logback不同文件

java - 解析JSON JAVA中的复杂字符串

c++ - 为什么这里的大括号和圆括号初始化之间存在差异?

java - 哪种方法更好?静态方法中的 ArrayList 很困惑

python - Python 3 的静态类属性

java - 比较数组值和 HashMap

c# - 获取在 .NET 3.5 中的 Lambda 表达式中使用的属性名称

java - 合并 Map<String, List<String> Java 8 Stream

在 C 中调用带有全局变量的静态函数

java - 在Java中分割以 "."结尾的段落并在点后换行