Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax for specifying a method reference to a generic method

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).

like image 823
kevin gomes Avatar asked Jul 06 '15 11:07

kevin gomes


People also ask

What is the syntax for generic function?

The syntax for a generic method includes a list of type parameters, inside angle brackets, which appears before the method's return type. For static generic methods, the type parameter section must appear before the method's return type.

What is a generic class write its syntax?

A Generic class simply means that the items or functions in that class can be generalized with the parameter(example T) to specify that we can add any type as a parameter in place of T like Integer, Character, String, Double or any other user-defined type.

How do you specify a generic type in Java?

To update the Box class to use generics, you create a generic type declaration by changing the code "public class Box" to "public class Box<T>". This introduces the type variable, T, that can be used anywhere inside the class. As you can see, all occurrences of Object are replaced by T.


2 Answers

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;
like image 82
Keppil Avatar answered Nov 15 '22 14:11

Keppil


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.

like image 30
ZhongYu Avatar answered Nov 15 '22 15:11

ZhongYu