1

I have a generic class that has a method which needs to know the runtime type:

public class SomePOJO<TYPE> {
    // ... lots of code

    public void doSomething() {
        // Obtain runtime type of TYPE and do something with it.
    }
}

I tried following the most upvoted answer of this question, and implemented doSomething() like so:

public void doSomething() {
    //                                                            |<-- error starts here
    Class clazz = (Class)((TYPE)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}

However this is throwing a compiler error:

The method getActualTypeArguments() is undefined for the type TYPE

I am compiling against JDK 1.6u34 - where am I going wrong - and why?

halfer
  • 19,824
  • 17
  • 99
  • 186
IAmYourFaja
  • 55,468
  • 181
  • 466
  • 756

1 Answers1

0

As it was mentioned in comments, due to type erasure you cannot get type in runtime. I would suggest to use a factory method like:

class SomePOJO<TYPE> {
    // Variable to store runtime type
    Class<TYPE> klass;
    private SomePOJO(Class<TYPE> klass) {
        this.klass = klass;
    }

    // Lots of code

    public void doSomething() {
        // Do what you want with type
        System.out.println(klass);
    }

    // Static factory method
    public static <T> SomePOJO<T> createPojo(Class<T> klass) {
        // Save class object that represents type to SomePOJO instance
        return new SomePOJO<T>(klass);
    }
}

It will help you to preserve type for doSomething() method.

Ivan Mushketyk
  • 8,107
  • 7
  • 50
  • 67