Java 从KType检索注释
我有一个简单的Java 从KType检索注释,java,reflection,annotations,jvm,kotlin,Java,Reflection,Annotations,Jvm,Kotlin,我有一个简单的类型\u USE注释: @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER}) public @interface Cool { } 以及以下Kotlin类示例: class Item( id: Long? = null, var names: List<@Cool String> = emptyLis
类型\u USE
注释:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER})
public @interface Cool {
}
以及以下Kotlin类示例:
class Item(
id: Long? = null,
var names: List<@Cool String> = emptyList())
类项目(
id:Long?=null,
变量名称:List=emptyList())
有没有办法使用Java反射提取注释
Item.class.getMethod(“getName”).getAnnotatedReturnType()
将丢失注释,与获取字段相同
我能从Kotlin那里得到注释吗
Item::class.memberProperties.elementAt(0).returnType
返回一个带有注释的KType
,但我看不到提取它的方法。也不从KType
获取AnnotatedType
,即使我有JDK8扩展
我看到的只是KType#javaType
,但它返回Type
,而不是AnnotatedType
。。。因此它再次松开注释。编辑:。还没有目标版本,但其优先级已设置为“主要”。这在Kotlin 1.3中已修复
TL;医生:没有
用
@Cool
注释的项是第一个类型参数,因此您需要检索它:
val type = Item::class.memberProperties.elementAt(0).returnType
val arg = type.arguments[0]
println(arg) // KTypeProjection(variance=INVARIANT, type=@Cool kotlin.String)
不幸的是,似乎没有办法检索KType
上的注释(如您所述)
奇怪的是,这是一个非常内在的过程。查看的源代码显示,toString
是通过ReflectionObjectRenderer.renderType(type)
实现的,(其中type是KotlinType
),它被委托给描述符renderer.FQ\u NAMES\u IN\u TYPES
,我们可以看到是
呈现程序检查该类型是否为kotlin.reflect.jvm.internal.impl.descriptors.annotations.Annotated
的子类,然后访问其annotations
属性
我试过这个:
val retType = Item::class.memberProperties.elementAt(0).returnType
val arg = retType.arguments[0]
println(arg) // KTypeProjection(variance=INVARIANT, type=@Cool kotlin.String)
val type = arg.type!!
println(type)
val field = type::class.memberProperties.first { it.name == "type" }
val kotlinType = field.call(type) as Annotated
println(kotlinType)
println(kotlinType.annotations)
不幸的是,org.jetbrains.kotlin.types.KotlinType
,我得到了一个ClassNotFoundException
,因此该选项不存在了
同样奇怪的是,KType
不是KAnnotatedElement
的子类型(这就是为什么它没有注释
属性)
我想这可能是一个疏忽,因为
ktypeempl
包装了一个KotlinType
,它确实包含注释。不是来自Java,因为“属性”的概念Java中不存在,它的注释作为字符串元数据保留或应用于合成方法。@Moira但此注释正好位于string
类型上,而不是属性上。所以它没有理由变得不可用……是的,但这是属性(names
)的类型参数。如果查看反编译的类,您会发现它没有编译成注释。@Moira好的,谢谢。有没有一种方法仍然可以使用Kotlin interop utils恢复它,就像JvmClassMappingKt
或类似的方法一样?或者从Kotlin自身获得AnnotatedType
?我甚至无法从Kotlin那里得到注释,因为KType
没有提供明显的方法。没想到会这样。感谢您的详细分析!这是令人恼火的-我刚刚遇到一个我自己需要它的案例:/希望有一天它能得到修复,因为它已经成为一个问题好几年了…显然,根据问题追踪者的说法,这最终在Kotlin 1.3中得到了修复。