Method References to Generics

Java-Method References to Generics

Method References to Generics

You can use method references with generic classes and/or generic methods. For example, in the following program, MyClass is a non-generic class that contains a static generic method called showData( ). This method print the elements in an specified array. Notice how the generic type argument is specified. For example, its first call in main( )MyClass::<Integer>showData  passes the type argument Integer. Notice that it occurs after the ::. This syntax can be generalized: When a generic method is specified as a method reference, its type argument comes after the :: and before the method name. It is important to point out, however, that explicitly specifying the type argument is not required in this situation because the type argument would have been automatically inferred. In cases in which a generic class is specified, the type argument follows the class name and precedes the :: .

Program

Method References to Generics

Program Source

interface Data<T> {

    void myData(T[] tarray);

}
class MyClass {

    static <T> void showData(T[] tarray) {
 
        for (T v : tarray) {
 
            System.out.print("["+v+"] ");
    }
    System.out.println();
   }
}

public class Javaapp {

     static <T> void callShowData(Data<T> daobj, T[] tarray) {
 
        daobj.myData(tarray);
     }

     public static void main(String[] args) {

        Integer[] ivals = {10,20,30,40,50,60,70,80,90};
        String[] svals = {"Ten","Twenty","Thirty","Forty","Fifty"};
 
        callShowData(MyClass::<Integer>showData, ivals);
        callShowData(MyClass::showData, ivals);
 
        callShowData(MyClass::<String>showData, svals);
        callShowData(MyClass::showData, svals);
     }
}

Leave a Comment