Monday, April 18, 2011

Writing generic methods

A Generic class containing a type parameter affects the entire class, but a generic method containing one or more type parameters affects that particular method only. So it means that a non-generic class can contain a mixture of generic and non-generic methods.


Example:

public class GenericMethods
{
    static <T> void printType(T anyType)
    {
        System.out.println(anyType.getClass().getName());
    } 
 
//using generic method
public static void main(String[] args) 
    {
        GenericMethods.printType(String.class);
        GenericMethods.printType(new String(""));
    }
}

If we look at the way in which a Generic method is declared, we find that the static method printType() has a return type void and it takes a single parameter called T. Here T stands for any parametric type which can be substituted with any of the Java types by the Clients. Since we have introduced a parameter T, it should be defined. But where? It should be defined in the method definition itself just before the return type of the method ().

The moral is whenever we have different type parameters in a method, it should be defined in the method definition. For example, consider the following method that has two type parameters A and B and they are defined before the return type of the method separated by commas.


<A, B> void genericMethod2Parameters(A aType, B bType)
{
    // Something here.
}


No comments:

Post a Comment

Chitika