11

我在“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;
    }
}

以下陈述有效

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

关于上述代码的解释,提出了两点

1 - 当泛型方法被指定为方法引用时,其类型参数::位于方法名称之后和之前。

2 - 在指定泛型类的情况下,类型参数在类名之后并在::.

我的查询:-

上面的代码是第一个引用点的例子

有人可以为我提供一个实现第二个引用点的代码示例吗?

(基本上我不明白引用的第二点)。

4

2 回答 2

2

第二个引用点只是表示类型参数属于类。例如:

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

然后会这样调用:

SomeTest<Integer> mRef = new MyClass<Integer>() :: myGenMeth;
于 2015-07-06T11:58:36.817 回答
2

例如

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

实际上我们这里不需要类型参数;类型推断将负责

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

但是在类型推断失败的情况下,例如当将此方法引用传递给没有足够的推断约束的泛型方法时,可能需要指定类型参数。

于 2015-07-06T15:06:43.353 回答