Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eclipse shortcut to generate simple assignment in constructor?

Tags:

java

eclipse

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 !

like image 633
Albert Gan Avatar asked Sep 12 '12 03:09

Albert Gan


People also ask

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.

What is a constructor in Eclipse?

Constructors unlike Methods is a block of code that lets you initialize variables immediately an object is created. Methods can be created and called later but with constructors, initialization is done immediately. Constructors have the same name as the class name and is called when an object of the class in created.


1 Answers

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.

like image 86
Bill Avatar answered Oct 15 '22 09:10

Bill