Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a shortcut for adding fields to existing constructor in Eclipse?

Is there any shortcut in Eclipse that allows me to add a field to the argument list of an existing constructor?

Example:

I hava this class:

public class A {
    int a;
    int b;

    public A(int a, int b) {
        this.a = a;
        this.b = b;
    }
}

when i add a field int c (or many fields) i want to add it to the argumentlist of the constructor and assign the parameter to the field:

public class A {
    int a;
    int b;
    int c; //this is new

    public A(int a, int b, int c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }
}

i currently do this by creating the parameter manually and then press CTRL + 1and then choose "assign parameter to field"

but if i add more than one field at once this isn't really a good solution imho.

I don't want to create a new constructor!

like image 330
Philipp Sander Avatar asked Nov 12 '13 14:11

Philipp Sander


People also ask

What is the shortcut to create constructor in Eclipse?

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 the shortcut for system out Println in eclipse?

To get System. out. println() line in eclipse without typing the whole line type sysout and press Ctrl + space.

What is a default constructor Java?

Default Constructor - a constructor that is automatically created by the Java compiler if it is not explicitly defined.


2 Answers

I would use the "change method signature" refactoring first (option+command+c on mac) to add the extra parameter(s) to the constructor. This way existing code that calls the constructor can pass sensible default as parameters (if you like). Then choose as many times CTRL+1 to quick fix the new fields into the class as you suggested.

like image 155
Jurgen Vinju Avatar answered Sep 20 '22 07:09

Jurgen Vinju


To use this shortcut in Intellij the variable must be final and private.

  1. Declare your variable as final.

Ex: private final String name;

  1. In MAC System the shortcut is Option+Return, i believe in windows is Alt+Enter.

  2. Then Click in Add constructor parameter.

Have fun!

like image 34
Rafael Filipake Avatar answered Sep 18 '22 07:09

Rafael Filipake