From Gossip@Openhome

Java Gossip: ネΘン

眤ㄏノClassnewInstance()よ猭ㄓ龟ㄒてンㄒ 
Class c = Class.forName(args[0]);
Object obj = c.newInstance();
 

狦更摸﹚竡Τ礚把计篶ㄧΑ玥ㄏノ硂贺よΑㄓ篶ぃ﹚﹍把计ン狦眤璶笆篈更のネΘン﹚把计玥璶﹚把计摸眔ConstructorンㄏノConstructornewInstance()﹚把计

ㄒㄓ弧и﹚竡Student摸

  • Student.java
package onlyfun.caterpillar;

public class Student {
private String name;
private int score;

public Student() {
name = "N/A";
}

public Student(String name, int score) {
this.name = name;
this.score = score;
}

public void setName(String name) {
this.name = name;
}

public void setScore(int score) {
this.score = score;
}

public String getName() {
return name;
}

public int getScore() {
return score;
}

public String toString() {
return name + " " + score;
}
}

礛笆篈更よΑㄓ笆篈ネΘン
  • NewInstanceDemo.java
package onlyfun.caterpillar;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class NewInstanceDemo {
public static void main(String[] args) {
Class c = null;

try {
c = Class.forName(args[0]);

// ﹚把计篈
Class[] params = new Class[2];
params[0] = String.class;
params[1] = Integer.TYPE;

Constructor constructor =
c.getConstructor(params);

// ﹚把计ず甧
Object[] paramObjs = new Object[2];
paramObjs[0] = "caterpillar";
paramObjs[1] = new Integer(90);

// 龟ㄒて
Object obj = constructor.newInstance(paramObjs);
System.out.println(obj);

} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}

磅︽ㄒ
java onlyfun.caterpillar.NewInstanceDemo onlyfun.caterpillar.Student
caterpillar 90