有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java的方法引用

根据Oracle DocumentationString::compareToIgnoreCase也是一个有效的方法引用,我的问题是compareToIgnoreCase不是一个静态方法,换句话说,compareToIgnoreCase必须附加到一个特定的String实例。那么,当我使用String::compareToIgnoreCase时,JDK如何知道我引用了String的哪个实例呢


共 (3) 个答案

  1. # 1 楼答案

    考虑下面的例子,使用^ {CD1>},这也是一个实例方法。

    它在这种情况下工作,因为正在处理的流项与正在调用的方法的类的类型相同。因此,该项实际上直接调用该方法

    所以

    Stream.of("abcde").map(String::toUpperCase).forEach(System.out::println);
    

    String::toUpperCase调用将与"abcde".toUpperCase()相同

    如果你做了这样的事:

    Stream.of("abcde").map(OtherClass::toUpperCase).forEach(System.out::println);
    

    “abcde”不是OtherClass的类型,因此OtherClass需要如下所示,流才能工作

    class OtherClass {
        public static String toUpperCase(String s) {
           return s.toUpperCase();
        }
    } 
    
  2. # 2 楼答案

    这就好像还有一个额外的参数,即实际的实例

    例如String::compareToIgnoreCase

    ToIntBiFunction<String, String> func = String::compareToIgnoreCase;
    int result = func.applyAsInt("ab", "cd");    // some negative number expected
    

    我们得到一个ToIntBiFunction——一个返回int的双参数函数——因为结果是一个int,第一个参数对应于compareToIgnoreCasethis,第二个函数参数是传递给compareToIgnoreCase的参数


    也许简单一点:

    ToIntFunction<String> f = String::length;  // function accepting String, returning int
    int length = f.applyAsInt("abc");          // 3
    

    length不接受任何参数,但函数的第一个参数用作调用实例length


    上面的例子非常抽象,只是为了说明所涉及的类型。这些函数大多直接用于某些方法调用,不需要使用中间变量

  3. # 3 楼答案

    String::compareToIgnoreCase没有像str1.compareToIgnoreCase(str2)那样使用。 它实际上被用作比较器。 你可以把它比作

    Arrays.sort(someIntegerArray, Collections.reverseOrder()) 
    

    但在这种情况下,它将是

    Arrays.sort(someStringArray, String::compareToIgnoreCase)