开发者

Can I generate fields automatically in eclipse from a constructor?

When I'm coding in eclipse, I like to be as lazy as possible. So I frequently type something like:

myObject = new MyClass(myParam1, myParam2, myParam3);

Even though MyClass doesn't exist and neither does it's constructor. A few clicks later and eclipse has created MyClass with开发者_JAVA百科 a constructor inferred from what I typed. My question is, is it possible to also get eclipse to generate fields in the class which correspond to what I passed to the constructor? I realize it's super lazy, but that's the whole joy of eclipse!


If you have a class A.

class A{
    A(int a |){}
}

| is the cursor. Crtl + 1 "assign parameter to new field"

Result:

class A{
    private final int a;
    A(int a){
        this.a = a;
    }
}

This works also for methods:

    void method(int b){}

Will result in:

    private int b;
    void method(int b){
        this.b = b;

    }


I know you can do the other way round. Define the fields and let Eclipse generate a constructor using these fields for you: Source | Generate Constructor using Fields


Since Eclipse Neon it is possible to assign all parameters to fields.

Using the quick assist Ctrl + 1 it suggest Assign all parameters to new fields. You can call for the quick assist if the cursor is anywhere between the parenthesis of the constructor.

This option is available for methods as well.

source

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜