Rayden78
Rayden78

Reputation: 43

Getting class from generic not working

I'm really confused right now. I'm using following code in another project without any problems:

public class ReadOnlyTable<T extends Model> implements ReadOnly<T> {
protected at.viswars.database.framework.core.DatabaseTable datasource;
private boolean debug = true;

protected ReadOnlyTable() {
    initTable();
}

protected void reloadDataSource() {
    initTable();
}

private void initTable() {
    boolean readOnlyClass = false;
    if (getClass().getSuperclass().equals(ReadOnlyTable.class)) readOnlyClass = true;

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

The last line will run without problems. Now i made a second project and as i had problems with reading out the Class i tried to do the most simple case possible:

public class GenericObject<T> implements IGenericObject<T> {
public GenericObject() {
    init();
}

private void init() {
    Class<T> clazz = (Class<T>)((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}

}

This class is instanciated here:

        GenericObject<String> go = new GenericObject<String>();

In my second example i will always receive following error message:

Exception in thread "main" java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType

What i am missing?? This drives me crazy. Any help is appreciated!

Upvotes: 2

Views: 22078

Answers (2)

newacct
newacct

Reputation: 122439

It is impossible to retrieve String from go. The type parameter of an object instantiation expression (new GenericObject<String>()) is not present anywhere at runtime. This is type erasure.

The technique you are trying to use concerns when a class or interface extends or implements another class or interface with a specific type argument. e.g. class Something extends GenericObject<String>. Then it is possible to get this declaration information from the class object. This is completely unrelated to what you are doing.

Upvotes: 5

user000001
user000001

Reputation: 33317

You are calling getGenericSuperclass(), but your class does not have a generic superclass. Its superclass is Object, which cannot be cast to ParameterizedType as the error says.

You probably want to use getGenericInterfaces()[0], since your class only implements an interface.

More info in here: http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Class.html#getGenericInterfaces()

Upvotes: 3

Related Questions