[英]Java Reflection - Passing in a ArrayList as argument for the method to be invoked
[英]Passing an arraylist as argument to method
我有一個看起來像這樣的方法:
public Person(String name, Person mother, Person father, ArrayList<Person> children) {
this.name=name;
this.mother=mother;
this.father=father;
this.children=children;
}
但是,當嘗試創建一個有孩子的新人時,我遇到了以下問題:
Person Toby = new Person("Toby", null, null, (Dick, Chester));
即使Dick和Chester的定義都更進一步。 更具體地說,它抱怨Dick和Chester都不能解析為變量。 我是否必須制作一個臨時ArrayList並通過它?
謝謝。
是的,您不會像那樣將Dick
和Chester
傳遞給構造函數。
您將假設您確實有兩個名為Dick
和Chester
Person對象:
ArrayList<Person> children = new ArrayList<Person>();
children.add(Dick);
children.add(Chester);
Person Toby = new Person("Toby", null, null, children);
您正在構造函數中,因此需要一個ArrayList對象,因此必須傳遞它。 像您使用的那樣的符號(Dick, Chester)
在Java中沒有意義。
您可以使用varargs:
public Person(String name, Person mother, Person father, Person... children) {
...
this.children = Arrays.asList(children);
}
Person p = new Person("Foo", Mother, Father, Dick, Chester);
我個人將Person構造函數更改為:
public Person(String name, Person mother, Person father, Person... children)
{
}
... ...基本上意味着構造函數將創建自己的Person對象數組,因此對其進行調用,例如:
Person toby = new Person("Toby", null, null, childOne, childTwo, childThree);
要么:
Person toby = new Person("Toby", null, null);
您的示例看起來不像Java代碼。 首先,必須在使用它們之前定義Dick和Chester。 因此,必須在“ Toby”上方創建它們。 其次,圓括號不會為您創建列表。 您必須使用以下命令顯式創建一個數組列表:
new ArrayList<Person>()
如果您無法按照問題的注釋進行操作,請嘗試以下操作:
public Person(String name, Person mother, Person father, List<Person> children) {
this.name=name;
this.mother=mother;
this.father=father;
this.children=children;
}
在這里,我更改了簽名以將最后一個參數用作列表類型。
Person Toby = new Person("Toby", null, null, Arrays.asList(Dick, Chester));
此外,孩子們的簽名也必須改變。 這里的重點是使用更抽象的類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.