Benj
Benj

Reputation: 32398

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 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!

Upvotes: 17

Views: 3892

Answers (3)

Jaap
Jaap

Reputation: 765

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

Upvotes: 2

Thomas Jung
Thomas Jung

Reputation: 33092

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;

    }

Upvotes: 32

Grzegorz Oledzki
Grzegorz Oledzki

Reputation: 24251

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

Upvotes: 4

Related Questions