在Groovy中获取列表的泛型类型
我正在构建一个自动化的招摇过市插件。在这里,我浏览了带注释的类 当我们讨论String、Long等数据类型时,我使用simpleName方法就足够了 但是当我得到一个List、Set、Collection类时,我需要知道泛型类型 那我该怎么做呢 完成大部分工作的代码示例:在Groovy中获取列表的泛型类型,groovy,Groovy,我正在构建一个自动化的招摇过市插件。在这里,我浏览了带注释的类 当我们讨论String、Long等数据类型时,我使用simpleName方法就足够了 但是当我得到一个List、Set、Collection类时,我需要知道泛型类型 那我该怎么做呢 完成大部分工作的代码示例: class Foo { List<String> myString } class SomeUtilClass { static String dataType(Class<?> c)
class Foo {
List<String> myString
}
class SomeUtilClass {
static String dataType(Class<?> c) {
return c.simpleName
}
static List<String> dataTypes(Class<?> c) {
return c.metaClass.properties.findAll {MetaProperty metaProperty ->
metaProperty?.field != null
}.collect {dataType(it.type)}
}
}
SomeUtilClass.dataTypes(Foo) // ["List"] but I want something like ["List<String>"]
class-Foo{
列出myString
}
类SomeUtilClass{
静态字符串数据类型(c类){
返回c.simpleName
}
静态列表数据类型(c类){
返回c.metaClass.properties.findAll{MetaProperty MetaProperty->
元属性?.field!=null
}.collect{dataType(it.type)}
}
}
SomeUtilClass.dataTypes(Foo)/[“List”]但是我想要类似[“List”]
我找到了解决方案。我可以从缓存字段中查看泛型类型
请参见以下示例:
class SomeUtilClass {
static String dataType(Class<?> c) {
return c.simpleName
}
static List<String> dataTypes(Class<?> c) {
return c.metaClass.properties.findAll {MetaProperty metaProperty ->
metaProperty?.field != null
}.collect {findGenerics(it.type)}
}
static void findGenerics(CachedField t) {
t.field.genericType?.actualTypeArguments.collect {dataType(it)}
}
}
class-SomeUtilClass{
静态字符串数据类型(c类){
返回c.simpleName
}
静态列表数据类型(c类){
返回c.metaClass.properties.findAll{MetaProperty MetaProperty->
元属性?.field!=null
}.collect{findGenerics(it.type)}
}
静态void findGenerics(缓存字段t){
t、 field.genericType?.actualTypeArguments.collect{dataType(it)}
}
}
因为groovy是在JVM上运行的:这个问题几乎回答了我的问题,但似乎更多的是新实例的运行时。我不想检查对象。泛型在运行时会被删除。不仅在对象上,而且在类上。