簡體   English   中英

Java 8方法引用特定類型的任意對象的實例方法

[英]Java 8 Method reference to instance method of an arbitrary object of a particular type

為什么以下不起作用?

import java.util.function.Function;

public class MethodRefTest {
   public String passMeAround( String input ) {
      return input + " been passed to me";
   }

   public Function<String, String> testReferences() {
      final Function<String, String> f1 = MethodRefTest::passMeAround;
      return f1;
   }

   public static void main( String[] args ) {
      new MethodRefTest()
            .testReferences()
            .apply( "foo" );
   }
}

Javac告訴我:

MethodRefTest.java:14: error: invalid method reference
      final Function<String, String> f1 = MethodRefTest::passMeAround;
                                          ^
  non-static method passMeAround(String) cannot be referenced from a static context
1 error

我不明白為什么上下文是靜態的 我讀過這個,但它似乎沒有回答手頭的問題。

編輯

同樣根據oracle ,可以通過ContainingType::methodName “引用特定類型的任意對象的實例方法

編輯2

@ marko-topolnik幫我理解了我的錯誤。 Function<String, String> f1 = MethodRefTest::passMeAround; 指一個靜態方法String MethodRefTest.passMeAround(String)

BiFunction<MethodRefTest, String, String> f1 = MethodRefTest::passMeAround;

另一方面,指的是在apply子句中傳遞的any instance的實例方法。

BiFunction<MethodRefTest, String, String> f2 = MethodRefTest::passMeAround;
//call instance method
f2.apply(new MethodRefTest(), "some string");

因為你稱之為

MethodRefTest::passMeAround

你應該把它稱為

this::passMeAround

提供用於上下文的實例。

查看當前代碼的另一種方法是說MethodRefTest::passMeAroundBiFunction<MethodRefTest, String, String>並且此lambda形狀與目標站點不匹配。 所以,或者,你可能已經寫過了

public BiFunction<MethodRefTest, String, String> testReferences() {
  return MethodRefTest::passMeAround;
}

並在主要方法

final MethodRefTest t = new MethodRefTest();
t.testReferences().apply( t, "foo" );

你讀過的材料可能不夠有用,所以讓我擴展一下。

this::passMeAround

你得到一個lambda對象,它從創建它的上下文中捕獲this實例,但是

MethodRefTest::passMeAround

你會得到一個“純粹的”非捕獲lambda,它代表某些實例上指定方法的調用,帶有一些字符串參數,因此當你apply它時,你需要傳入兩者。

passMeAround更改為static:

 public static String passMeAround( String input ) {
      return input + " been passed to me";
   }

或者參考實例方法:

 public Function<String, String> testReferences() {
      final Function<String, String> f1 = this::passMeAround;
      return f1;
 } 

要回答關於上下文為什么是靜態的問題,這是因為::之前的部分是的名稱而不是實例的名稱。 如果您沒有實例,則只能訪問靜態成員。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM