java-自动生成值对象
作者:互联网
给定一个或多个接口,生成类实现的最佳方法是什么?
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,
}
类变量应从接口的getter方法派生.理想情况下,将处理接口中的协变返回类型.该实现应通过使用私有最终变量和构造函数实例化来实现不变性. 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中:菜单“源”,“生成hashcode()和equals()…”,即)
标签:compile-time,annotations,code-generation,runtime,java 来源: https://codeday.me/bug/20191024/1921265.html