Accessing source code from Java Annotation Processor

后端 未结 5 1339
悲哀的现实
悲哀的现实 2020-12-04 22:38

I am trying to access the actual original source code of a type from within a Java Annotation Processor. Is this possible somehow? Thanks!

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-04 23:28

    The Mirror API is an equivalent of the Reflection API, but at compile time. Reading the internal content of methods using this API is not possible. Anything else should be OK.

    If you really want to do this, then there might be hacks to get an input stream on the source files you want to read.

    • Hibernate Metamodel Generator reads XML files using Filer.getResource(), in XmlParser.getInputStreamForResource(). The problem is that only CLASS_OUTPUT and SOURCE_OUPUT are supported, so it might not be suitable for you.

    • The other solution involves finding out the path of the source file, and then just open a regular input stream. I have done this kind of dirty hack for AndroidAnnotations, to read the AndroidManifest.xml file at compile time. See AndroidManifestFinder.findManifestFile().

提交回复
热议问题