对 Java8 lambda 和自动生成的构造函数感到困惑?
Confused with Java8 lambda and auto generated constructor?
@RequiredArgsConstructor
class Foo {
@NonNull private final UnaryOperator<String> myStr;
@NonNull private final Runnable start, stop;
public foo (UnaryOperator<String> myStr) {
this(myStr, () -> {}, () -> {};
}
..
}
这一行是做什么的:
> this(myStr, () -> {}, () -> {});
> () -> {}
此 class 中没有其他构造函数。
我什至不明白如何阅读它。
来自 Lombok 的 @RequiredArgsConstructor
注释为您创建构造函数。
作为初学者,您应该避免使用 Lombok,因为涉及的代码生成太多。
@RequiredArgsConstructor
class Foo {
@NonNull private final UnaryOperator<String> myStr;
@NonNull private final Runnable start, stop;
public foo (UnaryOperator<String> myStr) {
this(myStr, () -> {}, () -> {};
}
//...
}
将是:
class Foo {
private final UnaryOperator<String> myStr;
private final Runnable start, stop;
public foo (UnaryOperator<String> myStr) {
this(myStr, () -> {}, () -> {};
}
public foo (UnaryOperator<String> myStr, Runnable start, Runnable stop) {
//Lombok generated checks from @NonNull
if(myStr == null) throw new NullPointerException();
if(start == null) throw new NullPointerException();
if(stop == null) throw new NullPointerException();
this.myStr = myStr;
this.start = start;
this.stop = stop;
}
//...
}
@RequiredArgsConstructor
class Foo {
@NonNull private final UnaryOperator<String> myStr;
@NonNull private final Runnable start, stop;
public foo (UnaryOperator<String> myStr) {
this(myStr, () -> {}, () -> {};
}
..
}
这一行是做什么的:
> this(myStr, () -> {}, () -> {});
> () -> {}
此 class 中没有其他构造函数。 我什至不明白如何阅读它。
来自 Lombok 的 @RequiredArgsConstructor
注释为您创建构造函数。
作为初学者,您应该避免使用 Lombok,因为涉及的代码生成太多。
@RequiredArgsConstructor
class Foo {
@NonNull private final UnaryOperator<String> myStr;
@NonNull private final Runnable start, stop;
public foo (UnaryOperator<String> myStr) {
this(myStr, () -> {}, () -> {};
}
//...
}
将是:
class Foo {
private final UnaryOperator<String> myStr;
private final Runnable start, stop;
public foo (UnaryOperator<String> myStr) {
this(myStr, () -> {}, () -> {};
}
public foo (UnaryOperator<String> myStr, Runnable start, Runnable stop) {
//Lombok generated checks from @NonNull
if(myStr == null) throw new NullPointerException();
if(start == null) throw new NullPointerException();
if(stop == null) throw new NullPointerException();
this.myStr = myStr;
this.start = start;
this.stop = stop;
}
//...
}