【发布时间】:2015-04-28 09:33:11
【问题描述】:
如果我有类似下面的代码作为构造函数,如果所有实例变量的名称与参数名称相同,是否有一种简单的速记方法可以在一行中执行所有实例变量初始化?
private Quiz(int id, String name, int creatorId, Date timeCreated,
int categoryId, boolean randomOrder, boolean multiPage,
boolean immediateCorrection, boolean allowPractice) {
this.id = id;
this.name = name;
this.creatorId = creatorId;
this.timeCreated = timeCreated;
this.categoryId = categoryId;
this.randomOrder = randomOrder;
this.multiPage = multiPage;
this.immediateCorrection = immediateCorrection;
this.allowPractice = allowPractice;
}
【问题讨论】:
-
我想没有办法。但我可能错了。
-
你在用spring吗?
-
@alfasin - 我也在考虑类似的思路......但这种方法会非常缓慢。 :)
-
如果您有更多实例变量,那么您可以使用构建器模式,也可以使用伸缩构造器模式或 JavaBeans 模式。作为有效的java builder模式更好用。 在面对许多构造函数参数时考虑使用构建器
标签: java constructor initialization instance-variables