Reputation: 2032
class Json<T>
{
@SerializedName( "T's type here" )
private final ArrayList<T> _bucket = new ArrayList<T>( 5 );
...
}
I'd like to know how (if possible) the generic parameters of a class can be determined at run-time. From what I've read this is possible with sub-classes of generic types, but I haven't been able to find out how to do it with the type itself. There's some great info in these links, but I'm not sure it's what I'm looking for.
http://blog.xebia.com/2009/02/07/acessing-generic-types-at-runtime-in-java www.artima.com/weblogs/viewpost.jsp?thread=208860
What I'm ultimately trying to accomplish, is to get Gson to serialize the '_bucket' variable above, as the class name of type 'T'.
I'd appreciate it if someone could point me in the right direction.
Upvotes: 1
Views: 673
Reputation: 116582
Typically you would sub-class this type to give concrete type, and then processing packages should be able to properly resolve type. Alternatively many packages have a concept of type reference of some kind ("type token"), which just uses anonymous class to provide type information so that deserializer can correctly infer intended type; I don't remember what class Gson uses bit it should have something like this available.
If the only thing you have is a runtime instance then you are out of luck, with the exception of having non-empty List and checking its type (as suggested).
Upvotes: 0
Reputation: 269797
The generic type is not available at runtime in the given example. Generic type information is only available via reflection if it was specified at compile-time—for example, if you defined a subclass SomeTypeJson extends Json<SomeType>
.
As a kludge, you could guess at the generic type by examining the contents of the List
, finding the most specific common superclass via reflection.
Upvotes: 6