【发布时间】:2021-03-29 21:58:33
【问题描述】:
以下面的代码为例。
可以自动生成MySuperInterfaceImpl(MyInterface myInterface, double myDouble)吗?
我更喜欢避免使用lombok.Builder,因为它会引入 NullPointerException 问题。
另外提到的是使用@lombok.experimental.Delegate和@lombok.AllArgsConstructor会交换构造函数,所以在这种情况下我会问如何生成MySuperInterfaceImpl(String myString, int myInt, long myLong, double myDouble)的构造函数。老实说,我更喜欢这种实现方式。
interface MyInterface {
String getMyString();
int getMyInt();
long getMyLong();
}
@lombok.Value
class MyInterfaceImpl implements MyInterface {
String myString;
int myInt;
long myLong;
}
interface MySuperInterface extends MyInterface {
double getMyDouble();
}
@lombok.Value
@lombok.AllArgsConstructor
class MySuperInterfaceImpl implements MySuperInterface {
String myString;
int myInt;
long myLong;
double myDouble;
/**
* It would be great if I could hide/automatically generate this constructor with an annotation
*/
MySuperInterfaceImpl(MyInterface myInterface, double myDouble) {
this(myInterface.getMyString(), myInterface.getMyInt(), myInterface.getMyLong(), myDouble);
}
}
@lombok.Value
@lombok.AllArgsConstructor
class MySuperInterfaceImpl2 implements MySuperInterface {
@Delegate MyInterface myInterface;
double myDouble;
/**
* It would be great if I could hide/automatically generate this constructor with an annotation
*/
MySuperInterfaceImpl(String myString, int myInt, long myLong, double myDouble)
this(new MyInterface() {
String myString() { return myString; }
int myInt() { return myInt; }
long myLong() { return myLong; }
}, myDouble);
}
}
【问题讨论】:
-
知道要使用哪个 MyInterface 实例作为委托意味着什么?
-
@MrR 完全是
MyInterface,而不是任何其他具体实现,如第二个MySuperInterfaceImpl构造函数所示
标签: java constructor interface annotations lombok