islamic_programmer
islamic_programmer

Reputation: 244

how to define class of generic type in java

I have a class with a generic type and I want to get the class of the generic type. I found a solution with the following code but when I use ProGuard for obfuscation, my app stops working.

Is there an other way of doing this?

public class comImplement<T> {

  private T _impl = null;

  public comImplement() {}

  public T getImplement() {

    if (_impl == null) {
      ParameterizedType superClass = 
        (ParameterizedType) getClass().getGenericSuperclass();
      Class<T> type = (Class<T>) superClass.getActualTypeArguments()[0];
      try {
        _impl = type.newInstance();
      } catch (Exception e) {
      }
    }
    return _impl;
  }
}

Upvotes: 1

Views: 195

Answers (1)

jdevelop
jdevelop

Reputation: 12296

You can not get the type of superclass unless it's parametrized with another generic class, e.g - List or something like that. Due to reification type parameters will be lost after compilation. You may want to solve the problem with passing instance of class you're about to create, to method "getImplement, like below:

public T getImplement(Class<T> clz) {
   // do your initialization there
}

another problem which might raise with your code - is race condition in case if the object is shared between several threads.

Upvotes: 2

Related Questions