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;
}
}
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 !
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With