java - 自动生成值对象

标签 java annotations runtime code-generation compile-time

给定一个或多个接口(interface),生成类实现的最佳方法是什么?

interface Vehicle
{
    Engine getEngine();
}

@Generated
class Car implements Vehicle
{
    private final Engine engine;

    public Car(Engine engine)
    {
        this.engine = engine;
    }

    public Engine getEngine()
    {
        return engine;
    }

    // generated implementation of equals, hashCode, toString, 
}

类变量应该派生自接口(interface)的getter 方法。理想情况下,将处理接口(interface)中的协变返回类型。实现应该通过使用私有(private)最终变量和构造函数实例化来支持不变性。应生成 equals、hashCode 和 toString 方法。

最佳答案

更简洁的方法是使用 CGLIB在运行时动态生成类。显然,您无法浏览源文件。

如果你需要源文件,你可以试试codemodel并做类似的事情:

JCodeModel cm = new JCodeModel();
x = cm._class("foo.bar.Car");
x.field(Engine.class, "engine");
for (PropertyDescriptor pd:    Introspector.
              getBeanInfo(Vehicle.class).getPropertyDescriptors()) {
    g = x.method(JMod.PUBLIC, cm.VOID, pd.getReaderMethod().getName()); 
    g.body()...
    s = x.method(JMod.PUBLIC, cm.VOID, "set" + pd.getName());
    s.body()...
}
hc = x.method(JMod.PUBLIC, cm.VOID, "hashCode"));
hc.body()...
cm.build(new File("target/generated-sources"));

或者如前所述,使用 IDE(在 Eclipse 中:菜单“Source”、“Generate hashcode() and equals()...”,即)

关于java - 自动生成值对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/746694/

相关文章:

java - PagerAdapter 问题

java - Spring Security 4 @AuthenticationPrincipal 为空,带有 core.annotation.AuthenticationPrincipal 但不是 web.bind.annotation.AuthenticationPrincipal

java - 使用 javax.validation 注解将空字符串转换为 null

Swift 泛型,类型在运行时首先已知

python - 这些排列算法的大 O 符号是什么

Java FIFO队列实现

java - 从一种方法到另一种方法,失去了真正的基本值(value)

hibernate - hibernate 4.1.4 中 all-delete-orphan 的注释

c# - 在 C# 中生成运行时代码(结构、类)

java - 如何访问 SOAP 消息元素?