Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I generate fields automatically in eclipse from a constructor?

Tags:

eclipse

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!

like image 889
Benj Avatar asked Nov 24 '09 10:11

Benj


People also ask

How to auto generate constructor in Java?

To generate constructor(s) from a superclass, just press Alt+Shift+S, C (or alternatively select Source > Generate Constructor from Superclass… from the application menu). A dialog pops up allowing you to select the constructor(s) you'd like to create.

What is generate constructor from superclass?

Generate constructor(s) from a superclassA dialog pops up allowing you to select the constructor(s) you'd like to create. Once you click Ok, Eclipse generates the constructor, together with a super() call. Here's an example of how to create a constructor in SecretMessage, that inherits from the class Message.


1 Answers

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;

    }
like image 133
Thomas Jung Avatar answered Oct 23 '22 00:10

Thomas Jung