Cristian Batista Cristian Batista - 4 months ago 18
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);
}


Array.get()
is only for ArrayList and there isn't any
HashSet.iterator()
as Util

Thanks!

Answer

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.