5

I have a static method which will return a custom type based on the type of the class,

public class GenericMethod {

    public static <T> T returnGeneric(Class<T> clazz) {
        return null;
    }

}

Now, I want to pass a class with a generic type in to it,

CustomType<String> type = GenericMethod.returnGeneric(CustomType.class);

Only problem is that the above statement gives and unchecked conversion warning.

I tried the workaround new CustomType<String>().getName() which is also not solving the problem.

Is there a right way to it, or the only solution is to use @SuppressWarnings ?

anoopelias
  • 9,240
  • 7
  • 26
  • 39
  • 1
    possible duplicate : http://stackoverflow.com/questions/3403909/get-generic-type-of-class-at-runtime ? – benzonico Oct 30 '13 at 08:40

4 Answers4

1

What you would/should like to try is this:

CustomType<String> type = GenericMethod.returnGeneric(CustomType<String>.class);

Unfortunately, because of type erasure there is no difference between CustomType<A>.class and CustomType<B>.class, hence this syntax is not supported by Java.

So my $.02: what you are asking for is not possible, so hang on to the @suppresswarnings...

GerritCap
  • 1,606
  • 10
  • 9
1

The best approach is to use a wrapper method and place all your warnings in a single place.

And the term "unchecked" means that the compiler does not have enough type information to perform all type checks necessary to ensure type safety.

Ashish
  • 735
  • 1
  • 6
  • 15
0

In theory you can't do it because of type erasure.

In practice though ;) you can do it because the information is actually in the .class files. The easiest way I know of is using Spring's GenericTypeResolver.

Have a look at it.

Simeon
  • 7,582
  • 15
  • 64
  • 101
  • There is no difference between theory and practice. You are misunderstanding what type erasure is. And class metadata is not relevant to this question. – newacct Oct 31 '13 at 01:56
0

As you said @Simeon "In theory you can't do it because of type erasure". You can use it only if you have subclasses of CustomType:

class GenericMethod {

  public static <T> T returnGeneric(Class<T> clazz) {
    try {
      return  clazz.newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
      e.printStackTrace();
    }
    return null;
  }

  public static void main(String [] args){
    CustomeType<String> ct = returnGeneric(StringCustomeType.class);
    System.out.println(ct);
  }
}

class StringCustomeType extends CustomeType<String> {
}

class CustomeType<T> {
}
Sergey Morozov
  • 4,528
  • 3
  • 25
  • 39