【发布时间】:2016-01-26 21:17:31
【问题描述】:
有没有办法从构造函数的参数中生成简单的赋值?
发件人:
public class MyClass {
public MyClass(String id, String name, String desc) {
}
}
加上一些神奇的捷径,它会变成:
public class MyClass {
public MyClass(String id, String name, String desc) {
this.id = id;
this.name = name;
this.desc = desc;
}
}
如果我们有生成这个的快捷方式就更好了(避免使用许多 'ctrl + 1' 来创建不存在的字段):
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;
}
}
更新
我找到了一种可以接受的方法来处理这个问题:
首先,我的典型用法:
我的带参数的构造函数通常是另一个类的 ctrl + 1 的输出。
例如,在我的代码中:
MyClass type = new MyClass("id", "name", "desc"); // the constructor doesnt exist yet
所以,我 ctrl + 1,创建构造函数,然后 tadaa,构造函数是 eclipse 创建的
现在,为了帮助我创建字段并从参数中为其分配值,我只需将光标放在构造函数参数上,ctrl + 1 --> 将参数分配给新字段 ,并对所有参数重复。
希望这会有所帮助!
【问题讨论】:
-
我认为 eclipse 中没有任何可用的快捷方式。
-
我也这么认为。这是当今程序员可以进行的为数不多的体育锻炼之一,不应该被淘汰。
-
感谢您的更新,这正是我想要的。