簡體   English   中英

具有靜態成員的非靜態訪問的Java 8類型推斷

[英]Java 8 type inference with non-static access of static members

考慮以下代碼:

class Test {

    void accept(Consumer<Integer> c) {}

    static void consumer(Integer i) {}

    void foo() {
        accept(this::consumer); // The method accept(Consumer<Integer>) in the type Test is not applicable for the arguments (this::consumer)
        accept(Test::consumer); // Valid
    }

}

前幾天,當我意外地以非靜態方式調用靜態方法時,遇到了這一情況。 我知道您不應該以非靜態的方式調用靜態方法,但是我仍然想知道,為什么在這種情況下為什么不能推斷類型呢?

實際錯誤是invalid method reference static bound method reference

如果您知道四種類型的方法引用,那么這才有意義:

  1. 引用靜態方法。
  2. 引用綁定的非靜態方法。
  3. 引用未綁定的非靜態方法。
  4. 引用構造函數

JLS說明:

如果方法引用表達式的格式為ReferenceType :: [TypeArguments]標識符,並且編譯時聲明為靜態,並且ReferenceType不是簡單名稱或限定名稱,則這是編譯時錯誤。

除了不良的設計之外,還有捕獲(綁定)接收器的性能開銷。

暫無
暫無

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

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