问题
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 + 1
and 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!
回答1:
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.
回答2:
To use this shortcut in Intellij the variable must be final and private.
- Declare your variable as final.
Ex: private final String name;
In MAC System the shortcut is Option+Return, i believe in windows is Alt+Enter.
Then Click in Add constructor parameter.
Have fun!
回答3:
Add a parameter to the constructor and press alt+Enter(Control Assist) and you will get an option to create field for parameter then press Enter. This is available in latest IntelliJ 2017.2.
回答4:
The only short command in that area, that I'm aware of, of is "generate constructor using fields", which is available when pressing Alt+S. Maybe this could be a little bit of help. Here is some further useful info on shortcuts.
http://www.vogella.com/articles/EclipseShortcuts/article.html
回答5:
- Copy any additional logic in the old constructor to the clipboard (none in your example).
- Delete the old constructor.
- Create new constructor with
ALT+insert
->constructor
->CTRL+A
->ENTER
- Paste any additional logic copied in step 1.
回答6:
You can try this
- Right click the java class
- Source->Generate Constructor using fields.
- Select super constructor to use and instance variables to add to the constructor.
回答7:
In Eclipse:
- In Constructor select new parameter
- press ctrl+1
- select "Assign parameter to new field"
New field will be created in and will be set in your constructor.
回答8:
Use alt+shift+s+o. Generate Constructor using fields window will appear, click the select all button and press OK, you will get constructor with all the fields initialised.
来源:https://stackoverflow.com/questions/19931207/is-there-a-shortcut-for-adding-fields-to-existing-constructor-in-eclipse