Cristian Batista Cristian Batista - 1 year ago 79
Java Question

How can I get an element of a HashSet with reflection?

I'm trying to get the type of an array elements. I got something like this:

Set<Foo> mySet = new HashSet<Foo>();

I have to take via reflection the 'Foo' as a String.
I tried something like this:

if (className.equals("java.util.HashSet")){
Object arrayElement = Array.get(value, 0);
isComplex = isComplex(field, arrayElement);

is only for ArrayList and there isn't any
as Util


Answer Source

The method to obtain the Foo is:

ParameterizedType listType = (ParameterizedType) field.getGenericType();
Class<?> stringListClass = (Class<?>) listType.getActualTypeArguments()[0];

But you must be sure that field is an Array/Collection/HashSet, else, will be an exception.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download