3

I have a generic static method and I want it to return Class object of the inserted actual generic type.

I have tried it like this:

@SuppressWarnings("unchecked")
public static <T> Class<T> getClassType() {

    Method thisMethod;
    try {
        thisMethod = CommonTools.class.getMethod("getClass", new Class<?>[0]);
    } catch (Exception ex) {
        //ErrorLog.error(ex.getMessage(), ex);
        return null;
    }

    Type returnType = thisMethod.getGenericReturnType();
    Type tType = returnType.getClass().getGenericSuperclass();
    ParameterizedType parameterizedType = (ParameterizedType) tType;
    Class<T> clazz = (Class<T>) parameterizedType.getActualTypeArguments()[0];

    return clazz;
}

My inspiration for this was found in google code morphia library, there they have used something like this:

(((Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]))

the difference between my code and their code is that they call it for finding generic type in a class - I want it to be used in a method.

My code does not work and it falls within the (Class) conversion line.

Do you have any ideas how to get the current generic type from a static method?

thanks

ondra
  • 73
  • 7
  • why is 2 times it should be public static Class getClassType() if i am not wrong. – Shivaraj Patil Oct 22 '14 at 13:12
  • and how should the method than know that T is a generic parameter? – ondra Oct 22 '14 at 13:17
  • I think you can create a family of classes by using . You could also write a factory instead, give your parent class a type enum and use the factory to convert your classes into specific types based on the enum value passed. – G_V Oct 22 '14 at 13:20
  • I want to use it from a static class, your solution is not what I am looking for – ondra Oct 22 '14 at 13:22

1 Answers1

1

It will not work. You get method getClass, which basically has return type Class<CommonTools>, and after that you are calling getActualTypeArguments, which will return Class<CommonTools>, because TypeArgument is CommonTools.

If you will call Class<CommonTools> ct = getClassType(); it will work, but then there is no point to have such info.

As far as I know there is no way to get that information because JVM erases all generic info at runtime. Simplest solution is that CommonTools will get Class<T> instance at creation, and will return it, but then it is not so common.

win_wave
  • 1,498
  • 11
  • 9
  • okay, so it is impossible in java to know the generic type in runtime of a method? – ondra Oct 22 '14 at 13:41
  • Yes, read here: http://docs.oracle.com/javase/tutorial/java/generics/erasure.html and here http://stackoverflow.com/questions/9548779/java-generics-accessing-generic-type-at-runtime – win_wave Oct 22 '14 at 13:44