【发布时间】:2020-12-20 05:24:28
【问题描述】:
我正在使用 Java 开发一个项目,对于一个类中的每个属性,我有以下方法:
private MyType property;
public MyType getProperty() {
return this.property == null ? null : this.property.value;
}
public MyType getPropertyElement() {
if (this.property == null)
this.property = new MyType();
return this.property.value;
}
public bool hasProperty() {
return this.property != null;
}
public void setProperty(MyType property) {
this.property = property;
}
此外,如果MyType 是一个列表,那么还有一个方法addProperty。
在 python 中,我无法通过使用元类或装饰我的类来实现此功能。 在 C++ 中,我可以使用宏来实现这种行为。在这两种情况下,我都会在“类编译”期间向类添加方法。
在Java中是否存在类似于其中之一的机制?是否有另一种模式可以实现这一点?
我看到了一个名为lombok 的库,它使用注释来生成代码。自己写这样的东西是不是很简单
【问题讨论】:
-
在 Python 中你不能?
标签: java macros decorator auto-generate