如果字段是Set<String>
如何从 Set
确定泛型的类型(在本例中 String
)?
我有这个方法来确定泛型类型:
private boolean isSetTypeOf( Set<?> set, Class<?> clazz )
{
for ( Object object : set )
{
if ( object.getClass().equals( clazz ) )
{
return true;
}
}
return false;
}
但是我无法将 Field 转换为 Set,因此无法使用此方法。
Field field = getTheField();
if ( ReflectionUtils.isType( field, Set.class )
{
// Error
if ( isSetTypeOf( field, clazz ) )
{
// do something
}
}
基本上我知道字段类型是集合,现在我需要知道集合所保存的对象类型,只有在这之后我才会使用该字段。
最佳答案
假设您已获得适当的 Field
键入对应于您的 Set
类中的 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);
}
}
对于Set<String>
输入字段,这将输出:
Parameterized type for : java.util.Set<java.lang.String>
class java.lang.String
使用isSetTypeOf
方法不会为您提供参数化类型,而是为您提供存储在 Set
中的元素的实际类型。 .
关于java - 如何在 Java 中将 Field 转换为 Set 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18159747/