有什么简化的方法吗?
switch (student.getYear())
case 1:
new FirstYear(student.getId(), student.getName());
break;
case 2:
new SecondYear(student.getId(), student.getName());
break;
case 3:
new ThirdYear(student.getId(), student.getName());
break;
default:
break;
FirstYear,SecondYear,ThirdYear类共享同一父类吗?
java中是否有任何方法可以传递子类并使用其构造函数?他们是否共享相同的构造函数结构?
即。
public static void registerStudent(final Class yearClazz) {
new yearClazz(student.getId(), student.getName()).save(); //???
}
像这样吗?
答案 0 :(得分:1)
您可以使用方法参考和功能接口。使用单个方法创建一个接口(可选地用@FunctionalInterface
注释),该接口采用一个学生ID和名称,并返回FirstYear / SecondYear / ThirdYear的父级。假设您调用该接口YearFactory
和方法makeYear
。然后FirstYear::new
,SecondYear::new
和ThirdYear::new
都是实现该接口的对象。
switch (student.getYear())
case 1:
fac = FirstYear::new;
break;
case 2:
fac = SecondYear::new;
break;
case 3:
fac = ThirdYear::new;
break;
default:
break;
public static void registerStudent(final YearFactory fac) {
fac.makeYear(student.getId(), student.getName()).save();
}