问题
I read the following code in "Java - The beginner's guide"
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.2 - In case in which a generic class is specified, the type argument follows the class name and precedes the
::
.
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).
回答1:
The second quoted point just means that the type parameter belongs to the class. 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;
回答2:
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, e.g. when passing this method reference to a generic method without enough constraints for inference, it might be necessary to specify the type arguments.
来源:https://stackoverflow.com/questions/31245127/syntax-for-specifying-a-method-reference-to-a-generic-method