{ bo...">

Syntax for specifying a method reference to a general method

I read the following code in "Java - A 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; } } 

Assume the following statement:

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

Two comments were made regarding the explanation of the above code.

1 - When a generic method is specified as a method reference, its type argument appears after :: and before the method name.

2 - In case a generic class is specified, the type argument follows the class name and is preceded by :: .

My request: -

The above code is an example of the first quoted point.

Can someone provide me some code example that implements the second quote?

(Basically, I do not understand the second quote).

+8
java generics method-reference
source share
2 answers

The second point quoted simply 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; } } 

Then it could be called like this:

 SomeTest<Integer> mRef = new MyClass<Integer>() :: myGenMeth; 
+2
source share

for example

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

Actually, a type argument is not needed here; output type will take care of

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

But in cases where type inference is not performed, for example. when passing this method, a reference to a general method without sufficient restrictions for output, you may need to specify type arguments.

+1
source share

All Articles