kotlin - 注释处理器:如何知道 Kotlin 类是否用 Element 的“内部”可见性修饰符标记
问题描述
我正在使用自动服务来处理一些注释,但我无法确定 Kotlin 类是否具有来自注释处理器 API 的“内部”可见性修饰符。
我在处理器中使用 KAPT 和 Kotlin。依赖项:
implementation group: 'org.jetbrains.kotlin', name: 'kotlin-reflect', version: "1.3.0-rc-190"
implementation files("${System.properties['java.home']}/../lib/tools.jar")
implementation 'com.squareup:kotlinpoet:1.0.0-RC2'
implementation "com.google.auto.service:auto-service:1.0-rc4"
kapt "com.google.auto.service:auto-service:1.0-rc4"
样本类:
@MyAnnotation
internal class Car
我在 process 方法中得到了 this 的 TypeElement
override fun process(annotations: MutableSet<out TypeElement>, roundEnv: RoundEnvironment): Boolean {
roundEnv.getElementsAnnotatedWith(MyAnnotation::class.java).forEach { classElement ->
if (classElement.kind != ElementKind.CLASS) {
error(...)
return true
}
classElement as TypeElement
但我不知道如何检测该类是否具有“内部”修饰符。
如果我这样做:classElement.modifiers
我得到这个:
关于如何检测“内部”修饰符的任何想法?
解决方案
当您的 Kotlin 代码转换为.class
表单时,没有internal
修饰符。但是当你反编译你.class
的 Kotlin 代码文件时,你会看到有一个@Metadata
注解。
此元数据注释以二进制形式为您提供有关 Kotlin 声明的一些信息。您可以使用Kotlinx-metadata来读取和修改.class
文件的元数据。
因此,您需要从中获取@Metadata
注释classElement
,然后使用 Flags fromkotlinx-metadata
来确定它是否具有内部修饰符:
例如:
override fun visitFunction(flags: Flags, name: String): KmFunctionVisitor? {
if (Flag.IS_INTERNAL(flags)) {
println("function $name is internal")
}
...
}
推荐阅读
- node.js - 创建一个 Graph 并将其作为图像返回到 nodejs 服务器上
- rust - 如何使用 tokio::io::BufReader 读取块
- python - 生成一个满足一些条件的数组
- java - 如何根据android中的另一个arrayList对arrayList进行排序
- python - 如何将嵌套响应存储在列表或字典中?
- python - QGIS - 如何导出地图集,单独的 pdf?
- typescript - 当参数是泛型时,返回类型 `this` 被破坏
- python-3.x - 使用 pip 和 pipenv 构建和安装本地包
- c++ - 在 C++11 中模拟类似 Arduino 的中断
- javascript - Tipsi-Stripe:无法从令牌创建源