简体   繁体   中英

How to cast a Field as a Set class in Java?

If a field is a Set<String> how to determine the type of generic from the Set (in this case String )?

I have this method that determines the generic type:

private boolean isSetTypeOf( Set<?> set, Class<?> clazz )
{
    for ( Object object : set )
    {
        if ( object.getClass().equals( clazz ) )
        {
            return true;
        }
    }
    return false;
}

But I cannot cast Field as a Set, thus cannot use this method.

Field field = getTheField();

if ( ReflectionUtils.isType( field, Set.class )
{
    // Error
    if ( isSetTypeOf( field, clazz ) )
    {
        // do something
    }
}

Basically I know that the field type is a Set, now I need to know the type of object that the set holds and only after that I will use that field.

Assuming that you have got the appropriate Field type corresponding to your Set type field in your class, you can use the following code to find out the type of Parameterized Type :

Type type = field.getGenericType();   // Get the generic type of the Field, 

if (type instanceof ParameterizedType) {
    System.out.println("Parameterized type for : " + type);

    ParameterizedType pType = (ParameterizedType) type;
    Type[] types = pType.getActualTypeArguments();

    for (Type aType: types) {
        System.out.println(aType);
    }
}

For Set<String> type field, this will output:

Parameterized type for : java.util.Set<java.lang.String>
class java.lang.String

Using isSetTypeOf method will not give you the parameterized type, but the actual type of the elements stored in the Set .

试试这个object.getClass().isAssignableFrom(clazz)

Do this

if ( isSetTypeOf( new HashSet().add(field), clazz ) )

instead of:

if ( isSetTypeOf( field, clazz ) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM