简体   繁体   English

Java:使用注释在编译时生成自定义Java代码

[英]Java: Generate custom Java code at compile time using annotations

How do I write a Java inner class with custom properties at compile time using annotations? 如何使用注释在编译时编写带有自定义属性的Java内部类?

For instance, I want this : 例如,我想要这个:

@Generate
class Person {
     String firstname, lastname;
}

to generate: 生成:

class Person {
    String firstname, lastname;

    public static class $Fields { 
           public static String firstname = "firstname";
           public static String lastname  = "lastname";
    } 
}

How can I write the interface: 我该如何编写界面:

@Retention(RetentionPolicy.SOURCE)
public @interface Generate {
     // ... 
}

I understand I need to do some kind of AST transformation to make this magical. 我知道我需要做一些AST转换才能让这个神奇。

I am also aware of project lombok, but I want to know what the least common denominator is with a simple example, preferably within one method, and preferably something that a good editor would consider automatically, for instance RetentionPolicy.SOURCE for the javac compiler, which can be used in Intellij IDEA. 我也知道项目lombok,但我想通过一个简单的例子知道最不常见的分母,最好是在一个方法中,最好是一个好的编辑器会自动考虑的东西,例如Javac编译器的RetentionPolicy.SOURCE ,可以在Intellij IDEA中使用。

Project lombok is a beast code wise and is tough place to start. 项目lombok是一个明智的野兽代码,是一个艰难的起点。

It must be simpler than that, is it not? 它必须比那更简单,不是吗?

Any ideas? 有任何想法吗?

You can do this by reflection, but your new class won't be an inner class; 你可以通过反思来做到这一点,但是你的新课程不会是一个内部阶级; but be warned, you will lose static type safety. 但请注意,您将失去静态类型的安全性。

It can be done in 2 steps: 它可以分两步完成:

  1. Read the annotated class via reflection and transform it into a String which represents the source code of your new class. 通过反射读取带注释的类,并将其转换为表示新类源代码的String。
  2. Write this string to file, compile this String using the Java compiler API and then load and instantiate the new class, all programatically; 将此字符串写入文件,使用Java编译器API编译此String,然后以编程方式加载和实例化新类; see exact steps here . 这里的确切步骤

Alternatives to achieving similar functionality can also be obtained by bytecode instrumentation (see cglib or javassist ) or maybe even with proxies . 实现类似功能的替代方案也可以通过字节码检测(参见cglibjavassist )或甚至代理来获得

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM