Friday, September 23, 2011

Generics in Java


I have often read in articles and forums that all Java Generics information is erased at compile time so that you cannot access any of that information at runtime. This is not entirely true though. It ispossible to access generics information at runtime in a handful of cases. These cases actually cover several of our needs for Java Generics information. This text explains these cases.
Here is a list of the topics covered in this text:
  1. The Generics Reflection Rule of Thumb
  2. Generic Method Return Type
  3. Generic Method Parameter Types
  4. Generic Field Types

The Generics Reflection Rule of Thumb

Using Java Generics typically falls into one of two different situations:
  1. Declaring a class/interface as being parameterizable.
  2. Using a parameterizable class.
When you write a class or interface you can specify that it should be paramerizable. This is the case with the java.util.List interface. Rather than create a list of Object you can parameterizejava.util.List to create a list of say String.
When runtime inspecting a parameterizable type itself, like java.util.List, there is no way of knowing what type is has been parameterized to. This makes sense since the type can be parameterized to all kinds of types in the same application. But, when you inspect the method or field that declares the use of a parameterized type, you can see at runtime what type the paramerizable type was parameterized to. In short:
You cannot see on a type itself what type it is parameterized to a runtime, but you can see it in fields and methods where it is used and parameterized. Its concrete parameterizations in other words.
The following sections take a closer look at these situations.

Generic Method Return Types

If you have obtained a java.lang.reflect.Method object it is possible to obtain information about its generic return type. This cannot be any of the Method objects in the parameterized type, but in the class that uses the parameterized type. You can read how to obtain Method objects in the text "Java Generics: Methods". Here is an example class with a method having a parameterized return type:
public class MyClass {

  protected List<String> stringList = ...;

  pulic List<String> getStringList(){
    return this.stringList;
  }
}
In this class it is possible to obtain the generic return type of the getStringList() method. In other words, it is possible to detect that getStringList() returns a List<String> and not just a List. Here is how:
Method method = MyClass.class.getMethod("getStringList", null);

Type returnType = method.getGenericReturnType();

if(returnType instanceof ParameterizedType){
    ParameterizedType type = (ParameterizedType) returnType;
    Type[] typeArguments = type.getActualTypeArguments();
    for(Type typeArgument : typeArguments){
        Class typeArgClass = (Class) typeArgument;
        System.out.println("typeArgClass = " + typeArgClass);
    }
}
This piece of code will print out the text "typeArgClass = java.lang.String". The Type[] arraytypeArguments array will contain one item - a Class instance representing the classjava.lang.StringClass implements the Type interface.

Generic Method Parameter Types

You can also access the generic types of parameter types at runtime via Java Reflection. Here is an example class with a method taking a parameterized List as parameter:
public class MyClass {
  protected List<String> stringList = ...;

  pulic void setStringList(List<String> list){
    this.stringList = list;
  }
}
You can access the generic parameter types of the method parameters like this:
method = Myclass.class.getMethod("setStringList", List.class);

Type[] genericParameterTypes = method.getGenericParameterTypes();

for(Type genericParameterType : genericParameterTypes){
    if(genericParameterType instanceof ParameterizedType){
        ParameterizedType aType = (ParameterizedType) genericParameterType;
        Type[] parameterArgTypes = aType.getActualTypeArguments();
        for(Type parameterArgType : parameterArgTypes){
            Class parameterArgClass = (Class) parameterArgType;
            System.out.println("parameterArgClass = " + parameterArgClass);
        }
    }
}
This code will print out the text "parameterArgType = java.lang.String". The Type[] arrayparameterArgTypes array will contain one item - a Class instance representing the classjava.lang.StringClass implements the Type interface.

Generic Field Types

It is also possible to access the generic types of public fields. Fields are class member variables - either static or instance variables. You can read about obtaining Field objects in the text "Java Generics: Fields". Here is the example from earlier, with an instance field called stringList.
public class MyClass {
  public List<String> stringList = ...;
}
Field field = MyClass.class.getField("stringList");

Type genericFieldType = field.getGenericType();
    
if(genericFieldType instanceof ParameterizedType){
    ParameterizedType aType = (ParameterizedType) genericFieldType;
    Type[] fieldArgTypes = aType.getActualTypeArguments();
    for(Type fieldArgType : fieldArgTypes){
        Class fieldArgClass = (Class) fieldArgType;
        System.out.println("fieldArgClass = " + fieldArgClass);
    }
}
This code will print out the text "fieldArgClass = java.lang.String". The Type[] array fieldArgTypesarray will contain one item - a Class instance representing the class java.lang.StringClassimplements the Type interface.

No comments:

Post a Comment