Click to See Complete Forum and Search --> : Reflection Question with Map<K,V>


gte619n
December 28th, 2009, 09:05 PM
Hello,

I'm doing a little work with Java reflection and I seem to have hit a bit of a snag here. In my class, I have a field:

private Map<com.hs.MyKeyType,com.hs.MyValueType> myMap;

I am able to get the field using the getDeclaredFields() function of the class. I can also use: field.getType() function to get the type of the field as java.util.Map class; however, I can't seem to figure out a way to discover what class the Keys and values are.

Is it possible to know what the keys and values are at runtime?

Thanks for your help!

Evan

dlorde
December 29th, 2009, 12:24 PM
At runtime, generic type arguments are 'erased' to Object types. Java generics are just a compile-time thing.

If you extract a value or a key, you can use reflection to determine what actual type it is.

The outcome of any serious research can only be to make two questions grow where only one grew before...
T. Veblen

gte619n
December 29th, 2009, 02:05 PM
dlorde,

I was messing around this morning and I seem to have this working pretty consistently:

if (field.getType().isAssignableFrom( Map.class ))
{
Type type = field.getGenericType();
if (type instanceof ParameterizedType)
{
ParameterizedType pType = (ParameterizedType) type;
Class<?> keyType = (Class<?>) pType.getActualTypeArguments()[ 0 ];
Class<?> valueType = (Class<?>) pType.getActualTypeArguments()[ 1 ];
}
}

I thought that the generic types were thrown away as well, but it looks like this works. Is this due to my current Tomcat settings or is this reproducible across all environments?

E

dlorde
December 29th, 2009, 02:49 PM
Coo, interesting... as I understand it, after compilation your map ends up as a Map<Object, Object>, but it looks like the type argument declaration metadata is retained. ParameterizedType is part of the SDK, so I'd expect it to work in any context.

This is clearly something I need to catch up on :cool:

Thanks for the update :wave:

Shall I tell you the secret of the true scholar? It is this: every man I meet is my master in some point, and in that I learn of him...
R.W. Emerson

gte619n
December 29th, 2009, 03:47 PM
Ok great. I was worried about it being universally effective.

dlorde
December 29th, 2009, 05:09 PM
Ok great. I was worried about it being universally effective.

Don't take my word for it, I haven't tried it - I'm just saying I'd expect it to work anywhere because it's part of the SDK and I can't see how the server or OS has anything to do with it.

If it's important, try it out in the contexts you'll need it. Murphy's Law seems to show up when you don't...

Optimism is an occupational hazard of programming: testing is the treatment...
K. Beck

gte619n
December 29th, 2009, 05:10 PM
Will do.

Thanks man!