How to determine the class of a generic type?

JavaGenerics

Java Problem Overview


I'm creating a generic class and in one of the methods I need to know the Class of the generic type currently in use. The reason is that one of the method's I call expects this as an argument.

Example:

public class MyGenericClass<T> {
  public void doSomething() {
    // Snip...
    // Call to a 3rd party lib
    T bean = (T)someObject.create(T.class);
    // Snip...
  }
}

Clearly the example above doesn't work and results in the following error: Illegal class literal for the type parameter T.

My question is: does someone know a good alternative or workaround for this?

Java Solutions


Solution 1 - Java

Still the same problems : Generic informations are erased at runtime, it cannot be recovered. A workaround is to pass the class T in parameter of a static method :

public class MyGenericClass<T> {

    private final Class<T> clazz;

    public static <U> MyGenericClass<U> createMyGeneric(Class<U> clazz) {
	    return new MyGenericClass<U>(clazz);
    }

    protected MyGenericClass(Class<T> clazz) {
    	this.clazz = clazz;
    }

    public void doSomething() {
    	T instance = clazz.newInstance();
    }
}

It's ugly, but it works.

Solution 2 - Java

I was just pointed to this solution:

import java.lang.reflect.ParameterizedType;

public abstract class A<B> {
    public Class<B> g() throws Exception {
        ParameterizedType superclass =
            (ParameterizedType) getClass().getGenericSuperclass();

        return (Class<B>) superclass.getActualTypeArguments()[0];
    }
}

This works if A is given a concrete type by a subclass:

new A<String>() {}.g() // this will work

class B extends A<String> {}
new B().g() // this will work

class C<T> extends A<T> {}
new C<String>().g() // this will NOT work

Solution 3 - Java

Unfortunately Christoph's solution as written only works in very limited circumstances. [EDIT: as commented below I no longer remember my reasoning for this sentence and it is likely wrong: "Note that this will only work in abstract classes, first of all."] The next difficulty is that g() only works from DIRECT subclasses of A. We can fix that, though:

private Class<?> extractClassFromType(Type t) throws ClassCastException {
    if (t instanceof Class<?>) {
        return (Class<?>)t;
    }
    return (Class<?>)((ParameterizedType)t).getRawType();
}

public Class<B> g() throws ClassCastException {
    Class<?> superClass = getClass(); // initial value
    Type superType;
    do {
        superType = superClass.getGenericSuperclass();
        superClass = extractClassFromType(superType);
    } while (! (superClass.equals(A.class)));
     
    Type actualArg = ((ParameterizedType)superType).getActualTypeArguments()[0];
    return (Class<B>)extractClassFromType(actualArg);
}

This will work in many situations in practice, but not ALL the time. Consider:

public class Foo<U,T extends Collection<?>> extends A<T> {}

(new Foo<String,List<Object>>() {}).g();

This will throw a ClassCastException, because the type argument here isn't a Class or a ParameterizedType at all; it's the TypeVariable T. So now you would be stuck trying to figure out what type T was supposed to stand for, and so on down the rabbit hole.

I think the only reasonable, general answer is something akin to Nicolas's initial answer -- in general, if your class needs to instantiate objects of some other class that is unknown at compile-time, users of your class need to pass that class literal (or, perhaps, a Factory) to your class explicitly and not rely solely on generics.

Solution 4 - Java

i find another way to obtain the Class of the generic object

public Class<?> getGenericClass(){
         Class<?> result =null;
         Type type =this.getClass().getGenericSuperclass();

         if(type instanceofParameterizedType){
              ParameterizedType pt =(ParameterizedType) type;
              Type[] fieldArgTypes = pt.getActualTypeArguments();
              result =(Class<?>) fieldArgTypes[0];
        }
        return result;
  }

Solution 5 - Java

T can be resolved pretty easily using TypeTools:

Class<T> t = (Class<T>) TypeResolver.resolveRawArguments(
                                MyGenericClass.class, getClass());

Solution 6 - Java

I will elaborate on Christoph's solution.

Here is the ClassGetter abstract class:

private abstract class ClassGetter<T> {
	public final Class<T> get() {
		final ParameterizedType superclass = (ParameterizedType)
			getClass().getGenericSuperclass();
		return (Class<T>)superclass.getActualTypeArguments()[0];
	}
}

Here is a static method which uses the above class to find a generic class' type:

public static <T> Class<T> getGenericClass() {
	return new ClassGetter<T>() {}.get();
}

As an example of it's usage, you could make this method:

public static final <T> T instantiate() {
	final Class<T> clazz = getGenericClass();
	try {
		return clazz.getConstructor((Class[])null).newInstance(null);
	} catch (Exception e) {
		return null;
	}
}

And then use it like this:

T var = instantiate();

Solution 7 - Java

public class DatabaseAccessUtil {

EntityManagerFactory entitymanagerfactory;
EntityManager entitymanager;

public DatabaseAccessUtil() {
	entitymanagerfactory=Persistence.createEntityManagerFactory("bookmyshow");
	entitymanager=entitymanagerfactory.createEntityManager();
}

public void save  (T t) {
	entitymanager.getTransaction().begin();
	entitymanager.persist(t);
	entitymanager.getTransaction().commit();
}

public void update(T t) {
	entitymanager.getTransaction().begin();
	entitymanager.persist(t);
	entitymanager.getTransaction().commit();
}

public void delete(T t) {
	entitymanager.getTransaction().begin();
	entitymanager.remove(t);
	entitymanager.getTransaction().commit();
}

public Object retrieve(Query query) {
	return query.getSingleResult();
}
//call the method - retrieve(object,requiredclass.class)
public Object retrieve(Object primaryKey,class clazz) throws Exception {
    
	return entitymanager.find(clazz,primaryKey);	

}

}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJaap CoomansView Question on Stackoverflow
Solution 1 - JavaNicolasView Answer on Stackoverflow
Solution 2 - JavaChristophView Answer on Stackoverflow
Solution 3 - JavaSteven CollinsView Answer on Stackoverflow
Solution 4 - JavaJet GengView Answer on Stackoverflow
Solution 5 - JavaJonathanView Answer on Stackoverflow
Solution 6 - JavaintrepidisView Answer on Stackoverflow
Solution 7 - JavaAbul Kasim MView Answer on Stackoverflow