problems - java constructor shortcut intellij




Eclipse shortcut to generate simple assignment in constructor? (3)

Please see if it works.

Assign to local: Ctrl+2, L

Assign to field: Ctrl+2, F

Is there anyway to generate the simple assignments from the constructor's parameters ?

From :

public class MyClass {

  public MyClass(String id, String name, String desc) {

  }

}

and with some magic shortcut, it will become :

public class MyClass {

  public MyClass(String id, String name, String desc) {
    this.id = id;
    this.name = name;
    this.desc = desc;
  }

}

and even better if we have the shortcut to generate into this (to avoid many 'ctrl + 1's to create the non existing fields):

public class MyClass {
  private String id;
  private String name;
  private String desc;

  public MyClass(String id, String name, String desc) {
    this.id = id;
    this.name = name;
    this.desc = desc;
  }

}

update

I have found an acceptable way to deal with this :

First, my typical usage :

My constructor with the parameters are usually the output of ctrl + 1 from another class.

For example, in my code :

MyClass type = new MyClass("id", "name", "desc"); // the constructor doesnt exist yet

So, i ctrl + 1, create constructor, and tadaa, the constructor is created by eclipse

Now, to help my creating the fields and assigninig them values from the parameters, i just need to put the cursor on to the constructor parameter, ctrl + 1 --> assign parameter to new field, and repeat for all of the parameters.

Hope this helps !


You can press alt+shift+s+o.

A popup will come up - click ok and the constructor of your class with fields will get generated.


public class MyClass {
  private String id;
  private String name;
  private String desc;
}

If you type this much right click -> source -> generate constructor using fields

you can also generate all getters and setters. I have set these up for hot keys once they do not have them by default. But they require checking fields so it is not instant.





eclipse