![](/img/trans.png)
[英]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.