我有一个 Groovy 类,例如
class User {
List<Foo> someFoos = new ArrayList<Foo>()
List<Bar> someBars = new ArrayList<Bar>()
}
我可以在运行时使用
迭代这些属性def user = new User()
List<MetaProperty> setProperties = user.metaClass.properties.findAll {MetaProperty property ->
property.name.startsWith('some')
}
如果我检查每个属性的类型 Set
被返回
setProperties.each {MetaProperty setProperty ->
assert setProperty.type == Set
}
有什么方法可以在运行时为每个属性获取泛型类型参数(Foo
和 Bar
)?
我强烈怀疑我不能因为类型删除,但如果有人能证实我的怀疑,我将不胜感激。
最佳答案
是的,你可以。这些是字段定义,它们在运行时保留其类型定义。我会给你 java 代码,你也可以在 groovy 中使用它(我不知道 groovy 特定的解决方案)
Field[] fields = User.class.getDeclaredFields();
for (Field field : fields) {
ParameterizedType pt = (ParameterizedType) field.getGenericType();
Type concreteType = pt.getActualTypeArguments()[0];
}
关于java - 在运行时获取属性类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7235106/