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 :
static <T> void printType(T
anytype) Note :A type parameter (or type variable) is a variable which defines a generic type name.
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 |
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.
Ask Questions? Discuss: Generic Methods
Post your Comment