困惑于Java8 lambda和自动生成的构造函数?

时间:2016-12-01 20:36:34

标签: java-8 lombok

   @RequiredArgsConstructor
   class Foo {
        @NonNull private final UnaryOperator<String> myStr;
        @NonNull private final Runnable start, stop;

        public foo (UnaryOperator<String> myStr) {
            this(myStr, () -> {}, () -> {};
        }
    ..
    }

这一行做了什么:

> this(myStr, () -> {}, () -> {});
> () -> {}

此课程中没有其他构造函数。 我甚至不明白怎么读它。

1 个答案:

答案 0 :(得分:4)

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;
    }
    //...
}