java problems Eclipse shortcut to generate simple assignment in constructor?




java constructor shortcut intellij (4)

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 try:

  1. Go to Window->Preference->Java->Code Style->CodeTemplates

  2. Edit the constructor template to fit your requirement

  3. Edit the class template and add a constructor var.

Then, when you create a new class, Eclipse will automatically add the constructor into your code.


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.


Please see if it works.

Assign to local: Ctrl+2, L

Assign to field: Ctrl+2, F





eclipse