使用其他类的字段动态创建类

时间:2019-04-21 10:25:33

标签: java reflection aop

示例:

public class MyObject{
    @SerializedName("hello")
    @NotNull @MaxLength(256) @NotEmpty
    private String hello;
}

public class MyOtherObject{
    @SerializedName("world")
    @NotNull @MaxLength(512) @NotEmpty
    private String world;
}

如何动态生成MyDynamicHelloWorldObject类,使其等效于:

public class MyDynamicHelloWorldObject{
    @SerializedName("hello")
    @NotNull @MaxLength(256) @NotEmpty
    private String hello;

    @SerializedName("world")
    @NotNull @MaxLength(512) @NotEmpty
    private String world;
}

正在寻找解决方案,因为复制和粘贴会导致错误,尤其是将来更改代码时。

1 个答案:

答案 0 :(得分:0)

不确定是否推荐方式。您可以通过组合以下两个文件来创建文件MyDynamicHelloWorldObject.java,

String fileName1 = "MyObject.java";
String fileName2 = "MyOtherObject.java";

//read and write with try-with-resources
try (Stream<String> stream1 = Files.lines(Paths.get(fileName1));
    Stream<String> stream2 = Files.lines(Paths.get(fileName2));
    BufferedWriter writer1 = new BufferedWriter(new FileWriter("MyDynamicHelloWorldObject.java"))) {

    //first line 
    writer1.write("public class MyDynamicHelloWorldObject{\n");
    //merge two streams and skip first line as it has class name
    Stream.concat(stream1.skip(1),stream2.skip(1)).forEach(line->{try {
        writer1.write(line+"\n");
    } catch (IOException e) {
        //error handling
    }});
} catch (IOException e) {
    //error handling
}
}