package ObjectCollection;import java.lang.reflect.Constructor;public class Grouphog {
protected int number;
public Grouphog(int n) {
number = n;
}
public String toString() {
return "Grouphog #" +number;
}
public static void hogGroup(Class hogGroupClass) throws Exception {
Constructor con = hogGroupClass.getConstructor(new Class[] {int.class,int.class});
Grouphog g = (Grouphog)con.newInstance(new Object[] {new Integer(5),new Integer(6)});
System.out.println(g);
}
public static void main(String[] args) throws Exception {
hogGroup(Grouphog.class);
}
}运用Constructor 来构造有什么好处!? 迷惑
java的反射机制
要调用这个函数:
public static void hogGroup(Class hogGroupClass) throws Exception {
Constructor con = hogGroupClass.getConstructor(new Class[] {int.class,int.class});
Grouphog g = (Grouphog)con.newInstance(new Object[] {new Integer(5),new Integer(6)});
System.out.println(g);
}
必须得有:
public Grouphog(int ,int) {
//do init()
}
javac *.java class