先定義一個A類:
package test;
public class A {
private int a;
public A(){}
public A(int a){
this.a = a;
}
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
}
然後創建一個B類,在B類的main方法中動態加載A類,並生成A類的對象,調用有參數的構造函數:
package test;
import java.lang.reflect.Constructor;
public class B {
public B(){}
public static void main(String[] args) throws Exception
{
int i = 5;
A tempClass = (A)(Class.forName("test.A").newInstance());
Class[] parameter = new Class[]{int.class};
Constructor con = tempClass.getClass().getConstructor(parameter);
Object[] arg= new Object[] { i };
A a = (A)con.newInstance(arg);
System.out.println(a.getA());
}
}