静态方法和实例方法的方法参考

在 Java 中的实例方法的情况下,我无法掌握方法引用的概念

例如,在下面的示例中,编译器在列表行中给出错误。

我看过 String::toUpperCase 的例子。

我对 (1) String 是一个类而 toUpperCase 是实例方法这一点感到困惑。Java 允许 String::toUpperCase (2) 为什么在我的情况下不允许:- AppTest::makeUppercase

package mja;

import java.util.function.Function;
public class AppTest {

    public String makeUppercase(String source){
        return source.toUpperCase();
    }
    
    public void printFormattedString(String string, Function<String, String> formatter){
        System.out.println(formatter.apply(string));
    }
    
    public static void main(String[] args) {
        AppTest appTest = new AppTest();
        String source = "Hello World!";
        
        // Below statement compiled successfully
        appTest.printFormattedString(source, appTest::makeUppercase);

        // Getting error that non-static method can't be referenced from static context
        appTest.printFormattedString(source, AppTest::makeUppercase);
    }
}

以上是静态方法和实例方法的方法参考的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>