can I get .class from generic type argument?
Posted
by
Mike S
on Stack Overflow
See other posts from Stack Overflow
or by Mike S
Published on 2012-09-21T03:06:31Z
Indexed on
2012/09/21
3:38 UTC
Read the original article
Hit count: 126
I have the following class:
public abstract class MyClass<T extends Object> {
protected T createNewFromData(Reader reader){
GSON.fromJSON(reader,T.class); // T.class isn't allowed :(
}
}
How do I pass a Class<T> instance into there? Is there some wierd and wacky work around?
Is there a way to get a Class<T> reference other than from a pre-instantiated Object of type T? It won't let me do this either:
T t = new T();
Class<T> klass = t.class;
ANSWER BELOW
Thanks to the accepted answer, here is the solution:
Type type = new TypeToken<T>(){}.getType();
return gson.fromJson(reader, type);
© Stack Overflow or respective owner