Cristian Batista Cristian Batista - 8 months ago 37
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



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.