Thursday, July 3, 2014

Get Class Type of Generic Parameter in Java

Here is the process to get the Class Type of GenericParameter that was passed in to the Java Class.

We need to follow small tweak to make it work because Java Generics uses Type Erasure at Runtime.
Trick is: While creating Object, we need to create anonymous class. (So that getGenericSuperclass() will return target class)

Here is the requirement:
   Implement a Generic Transformer, which will transform input Objects to dynamic Objects based on class Type parameter.


import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Transformer;

public class GenTransformer implements Transformer {

public Class returnedClass() {
        ParameterizedType parameterizedType;
try {
parameterizedType = (ParameterizedType) getClass().getGenericSuperclass();
} catch (Exception e) {
throw new IllegalArgumentException("Instantiate your Transformer as anonymous class. (Ex: new GenTransformer() {})");
}

        @SuppressWarnings("unchecked")
        Class ret = (Class) parameterizedType.getActualTypeArguments()[0];
        return ret;
    }

@Override
public Object transform(Object arg0) {
Class cls = returnedClass();
return arg0 + "-" + cls.getName();
}

public static void main(String[] args) {
List names = new ArrayList();
names.add("Name1");
names.add("Name2");
List res1 = (List) CollectionUtils.collect(names, new GenTransformer(){});
System.out.println(res1);
}
}