编译时的 Java 代码转换

标签 java compilation code-translation

我想在将源代码传递给编译器之前转换 java 源代码在编译时。换句话说,我想创建一个能够转换的 预处理器

"bla bla bla" 

进入任何其他代码,例如:

new MyClass("bla", 3) 

我的实际动机是进行字符串加密,如 explained here

有些人建议编写自定义注释处理器,但据我了解注释:

  • 它们可用于生成新的类文件,但不能在传递给编译器之前转换现有代码
  • 它们似乎适用于包、类或方法级别,但不适用于方法主体/实现。

有些人建议使用 Spoon 或 ObjectsWeb ASM 等框架,但这些框架在现有代码库上学习和部署似乎很复杂。

我很高兴为这两种方法找到一个简单的 java 代码预处理示例。

有没有人看到任何聪明的代码转换方式,而不用完全改变现有的带有多个 ivy 模块的大型代码库?注释似乎是最好的方法,但我不明白该怎么做。

最佳答案

我认为您可以尝试 Project Lombok 中使用的相同技术

作者在 this interview 中大致解释了这一点。 :

What's going on under the hood? I.e., how does an annotation result in the boilerplate ending up in the bytecode?

Reinier: The annotation processor API only lets you create new files, it does not let you modify the file that has the annotation inside of it. Which is what Lombok does, so Lombok does not use the annotation processor API.

Instead, Lombok uses the annotation processor API only as a mechanism to inject itself into the compilation process. All annotation processors are initialized early in the compilation process, and Lombok modifies javac when it is initialized as an annotation processor. We change only one thing: The AST (the raw source code, parsed into a tree form) is first handed off to Lombok, which generates whatever needs to be generated, before javac continues.

How does lombok work?

也可以根据您的需要扩展 Project Lombok

关于编译时的 Java 代码转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10483423/

相关文章:

java - 在 Minecraft mod 中修改 .class 文件

java - 无法用maven编译Impala的前端

java - 从数组中随机播放特定对象

java - 如何将 List<实现接口(interface)的对象> 传递给方法?

eclipse - 为什么Eclipse不需要我配置JDK?

compiler-construction - 如何开始编写翻译器?可能吗

javascript - 在js中打印数组值

sql - 将查询从 Firebird 转换为 PostgreSQL

java - 从以下树状数据结构中获取所有可能的组合

Java简单的for循环不迭代