日期:2014-05-20 浏览次数:20816 次
package tw.com.javasorld; import java.lang.reflect.*; public class TestReflection03 { public static void main(String[] args) { Class c; Constructor constractor; Object obj ; try{ c= Class.forName("tw.com.javasorld.Person"); //调用有参数的构造方法 Class[] argTypes = new Class[]{String.class,int.class}; constractor = c.getConstructor(argTypes); obj = constractor.newInstance("中国",5000); System.out.println(obj); //调用无参方法的构造函数 constractor = c.getConstructor(); obj = constractor.newInstance(); System.out.println(obj); }catch(Exception e){ e.printStackTrace(); } } }
package tw.com.javasorld; public class Person { private int age; private String name; private int total; Person(){ super(); total++; } Person(String name,int age){ super(); this.name = name; this.age = age; total++; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public String toString(){ return "Name :" +name +"\tAge :" + age; } }