sec*_*ask 11 java eclipse templates
我需要自定义eclipse setter模板来返回这个对象,就像这样
public Person setName(String name){
this.name=name;
return this;
}
Run Code Online (Sandbox Code Playgroud)
但是Java-> Code Style-> Templates只允许我自定义setter body部分,而不是方法定义.有什么办法吗?
我担心我无法提供允许你为此修改Eclipse模板的解决方案,但是我可以建议你重新考虑一下你在这里做什么吗?
如果检查JavaBeans规范,您将看到以这种方式定义方法时,它们不再是有效的属性设置器.Setters应该有一个void
返回类型; 从长远来看,你可能会后悔创建这些非标准的bean.例如,尝试使用java.beans.Introspector
为您的类收集bean信息,您将看到找不到您的属性"setter".
我知道能够使用链式调用快速初始化bean是很好的,例如:
new Person().setName("John Smith").setDateOfBirth(...).setAddress(...)
Run Code Online (Sandbox Code Playgroud)
作为替代方案,我可以建议使用标准setter(返回void
),而是引入构建器方法,如:
public Person withName(String name) {
this.setName(name);
return this;
}
Run Code Online (Sandbox Code Playgroud)
您的快速单线构造如下所示:
new Person().withName("John Smith").withDateOfBirth(...).withAddress(...)
Run Code Online (Sandbox Code Playgroud)
我发现'with'前缀也很好.