简体   繁体   English

用于指定泛型方法的方法引用的语法

[英]Syntax for specifying a method reference to a generic method

I read the following code in "Java - The beginner's guide" 我在“Java - 初学者指南”中阅读了以下代码

interface SomeTest <T>
{
    boolean test(T n, T m);
}

class MyClass
{
    static <T> boolean myGenMeth(T x, T y)
    {
        boolean result = false;
        // ...
        return result;
    }
}

The following statement is valid 以下声明有效

SomeTest <Integer> mRef = MyClass :: <Integer> myGenMeth;

Two points were made regarding the explanation of the above code 关于上述代码的解释有两点

1 - When a generic method is specified as a method reference, its type argument comes after the :: and before the method name. 1 - 当泛型方法被指定为方法引用时,其类型参数位于::和方法名称之前。

2 - In case in which a generic class is specified, the type argument follows the class name and precedes the :: . 2 - 如果指定了泛型类,则type参数在类名后面,并在::之前。

My query:- 我的查询: -

The code above is the example of the first quoted point 上面的代码是第一个引用点的示例

Can someone provide me an example of code which implement the second quoted point? 有人能为我提供一个实现第二个引用点的代码示例吗?

(Basically I don't understand the second quoted point). (基本上我不明白第二个引用点)。

The second quoted point just means that the type parameter belongs to the class. 第二个引用点仅表示type参数属于该类。 For example: 例如:

class MyClass<T>
{
    public boolean myGenMeth(T x, T y)
    {
        boolean result = false;
        // ...
        return result;
    }
}

This would then be called like this: 然后将这样调用:

SomeTest<Integer> mRef = new MyClass<Integer>() :: myGenMeth;

For example 例如

  Predicate<List<String>> p = List<String>::isEmpty;

Actually we don't need the type argument here; 实际上我们这里不需要类型参数; the type inference will take care of 类型推断会照顾

  Predicate<List<String>> p = List::isEmpty;

But in cases type inference fails, eg when passing this method reference to a generic method without enough constraints for inference, it might be necessary to specify the type arguments. 但是在类型推断失败的情况下,例如,在没有足够的推理约束的情况下将此方法引用传递给泛型方法时,可能需要指定类型参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM