从TypeElement获取文件路径

huangapple 未分类评论43阅读模式
英文:

Get file path from TypeElement

问题

我正在编写一个注解处理器,用于生成一个包含从注解中读取的某些数据以及使用这些注解的文件路径的 JSON 文件(简单部分),问题是:我无法弄清楚如何获取与 TypeElement(被注解的元素)对应的文件。

我发现 TreePath API 应该可以做到这一点:

val instance = Trees.instance(processingEnv)
instance.getPath(element)

但似乎在我们使用的 JDK 版本中(AdoptOpenJDK OpenJDK Runtime Environment 1.8.0_242-b08)中并不可用 com.sun.source.util.Trees

我还尝试了以下方法:

val compiler: JavaCompiler = ToolProvider.getSystemJavaCompiler()
val fm = compiler.getStandardFileManager(null, null, null)
val locations = fm.getJavaFileObjects(element.toString())
println(locations.first().toUri())

但它没有为我提供一个有效的文件路径。

还有其他提示吗?

英文:

I'm writing an annotation processor that generates a JSON file containing some data read from the annotations (easy) and the file path where these annotations are used.

Problem: I cannot figure out how to get the file corresponding to a TypeElement (which is the annotated element).

I found that the TreePath api should do this:

val instance = Trees.instance(processingEnv)
instance.getPath(element)

but it seems that com.sun.source.util.Trees is not available in the jdk version we use (AdoptOpenJDK OpenJDK Runtime Environment 1.8.0_242-b08)

I also tried with

val compiler: JavaCompiler = ToolProvider.getSystemJavaCompiler()
val fm = compiler.getStandardFileManager(null, null, null)
val locations = fm.getJavaFileObjects(element.toString())
println(locations.first().toUri())

but it doesn't give me a valid path to the file.

Any other hint?

huangapple
  • 本文由 发表于 2020年4月8日 21:39:24
  • 转载请务必保留本文链接:https://java.coder-hub.com/61102073.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定