[英]How to instantiate class in Java where number of parameters in constructor of class under test is unknown through Reflection?
[英]How do I write a constructor for unknown number of parameters in java?
我基本上是为任何数量的学生可以申请的每门大学课程制作一个 class。 我想知道我怎样才能有一个构造函数,不管我的“学生”对象的数量是 1 还是 15 或更多......因为我知道有一种方法,只是不记得了......
import java.util.ArrayList;
public class Course {
String name;
ArrayList <Student>listofstudents=new ArrayList<>();
int noofStudents;
//The class Student is defined.
Course(String name,Student s1, Student s2){
this.name=name;
listofstudents.add(s1);
listofstudents.add(s2);
//Do I have to do this for every possible number of student?
}
}
正如您的其他答案所观察到的,构造函数可以像常规方法一样具有变量 arguments 。 但是,您应该考虑只说不。 也就是说,参加给定课程的学生是次要属性,您可以在没有他们的情况下将Course
放入有效的 state 中。 然后考虑不通过构造函数接受学生,而是使用一种或多种方法将学生添加到现有的Course
中。 (无论如何,您可能需要它。)然后在初始化Course
后通过该路线添加学生。
void addStudent(Student s) {
listofstudents.add(s);
}
void addStudents(Student ... s) {
if (s != null) {
listofstudents.addAll(java.util.Arrays.asList(s));
}
}
您可以使用可变参数。 变量 Arguments 是一种允许您创建具有任意数量的 arguments 的方法的技术。
import java.util.ArrayList;
public class Course {
String name;
ArrayList <Student>listofstudents=new ArrayList<>();
int noofStudents;
//The class Student is defined.
Course(String name,Student ... s){
Student [] stds = s;
this.name=name;
//your code
}
}
Varargs 使用起来很简单。 但是有一些规则我们必须牢记:
每次我们使用可变参数时,Java 编译器都会创建一个数组来保存给定的参数。
现在您可以通过这种方式使用构造函数:
new Course("Name");
new Course("Name", new Student());
new Course("Name", new Student(), new Student(), new Student());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.