Generic Methods

In this section,you will learn how you can create a single Generic method which can be called by passing arguments of different types.

Generic Methods

Generic Methods

You can create a single Generic method which can be called by passing arguments of different types. Depending on the argument type provided to the compiler , each method call is handled by compiler appropriately.

The following thing must be keep in mind when defining Generic Method :

  • The Generic method has a type parameter section which is enclosed by angel (< >)  brackets which should be placed before return type of method. For example :
  •         static <T> void printType(T anytype) 

    Note :A type parameter (or type variable) is a variable which defines a generic type name.

  • Type parameter section can have one or more type variable separated by commas(,) 

  • The passed argument(known as actual type arguments) replaces the type parameters which act as return type for the method.In other words, we can say that it(type parameters) acts as placeholder for passed argument to the method.   

  • The Generic method declaration is similar to any other method declaration.
  •  

EXAMPLE

In the below example, <T> acts as placeholder for the passed arguments to the Generic method "printClassnName" . This method prints two things : the passed argument package name & name of the runtime class of the passed argument..

package simpleCoreJava;

public class GenericMethodExample {

static <T> void printClassnName(T anyType) {
System.out.println(anyType.getClass().getPackage());
System.out.println(anyType.getClass().getName());
}
public static void main(String[] args) {
GenericMethodExample.printClassnName(String.class);
GenericMethodExample.printClassnName(new String(""));
GenericMethodExample.printClassnName(Integer.class);
GenericMethodExample.printClassnName(new Integer(3));
GenericMethodExample.printClassnName(GenericMethodExample.class);
}
}

OUTPUT :


package java.lang, Java Platform API Specification, version 1.6    
java.lang.Class
package java.lang, Java Platform API Specification, version 1.6
java.lang.String
package java.lang, Java Platform API Specification, version 1.6
java.lang.Class
package java.lang, Java Platform API Specification, version 1.6
java.lang.Integer
package java.lang, Java Platform API Specification, version 1.6
java.lang.Class

Download Source Code