Java リフレクションについて助けが必要です。添付のコードに基づいて、buildPersonDynamically メソッドで動的にクラス オブジェクトの ArrayList を返す方法がわかりません。ロジックは buildPerson メソッドのようなものです。MyMain.java を参照してください。
package reflection;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import reflection.builder.PersonBuilder;
import reflection.one.two.three.Person;
public class MyMain {
public static void main(String[] args) {
buildPerson(3);
buildPersonDynamically(3);
}
static void buildPerson(int total) {
PersonBuilder pb = new PersonBuilder();
pb.build(3);
ArrayList<Person> per = pb.getDataSet();
System.out.println(per.get(1).FirstName);
}
static void buildPersonDynamically(int total) {
try {
Class<?> c = java.lang.Class.forName("reflection.builder.PersonBuilder");
Object obj = c.newInstance();
Class<Integer> partypes = Integer.TYPE;
Method m1 = c.getMethod("build", partypes);
m1.invoke(obj, total);
Method m2 = c.getMethod("getFirstName", partypes);
Object objStr = m2.invoke(obj, 2);
System.out.println(objStr.toString()); // success
Method m3 = c.getMethod("getDataSet");
// Not sure how to get an ArrayList of Person dataSet dynamically.
// Example, want to get the FirstName from the m3.
}
catch (Throwable e) {
System.err.println(e);
}
}
}
package reflection.builder;
import java.util.ArrayList;
import reflection.one.two.three.Person;
public class PersonBuilder {
private ArrayList<Person> dataSet;
public ArrayList<Person> getDataSet() {
return dataSet;
}
public ArrayList<Person> build(int numberOfRecords) {
ArrayList<String> firstName = new ArrayList<String>();
ArrayList<String> lastName = new ArrayList<String>();
ArrayList<Integer> age = new ArrayList<Integer>();
ArrayList<String> emailAddress = new ArrayList<String>();
Person per;
this.dataSet = new ArrayList<Person>();
firstName.add("Barrack");
firstName.add("John");
firstName.add("Whitney");
firstName.add("Paris");
firstName.add("Britney");
lastName.add("Obama");
lastName.add("Lennon");
lastName.add("Houston");
lastName.add("Hilton");
lastName.add("Spears");
age.add(47);
age.add(60);
age.add(48);
age.add(32);
age.add(25);
emailAddress.add("barrack.obama@gmail.com");
emailAddress.add("john.lennon@gmail.com");
emailAddress.add("whitney.houston@gmail.com");
emailAddress.add("paris.hilton@gmail.com");
emailAddress.add("britney.spears@gmail.com");
if (numberOfRecords >= 5) numberOfRecords = 5;
for (int i=0; i < numberOfRecords; i++) {
per = new Person();
per.FirstName = firstName.get(i);
per.LastName = lastName.get(i);
per.Age = age.get(i);
per.EmailAddress = emailAddress.get(i);
this.dataSet.add(per);
}
return this.dataSet;
}
public String getFirstName(int a) {
return this.dataSet.get(a).FirstName;
}
}
package reflection.one.two.three;
public class Person {
public String FirstName;
public String LastName;
public int Age;
public String EmailAddress;
}