import java.lang.reflect.Constructor;
class Test
{
public static void main(String[] args) throws Exception
{
//第一种:获取字节码文件对象
Class<?> c1 = Class.forName("Person");
//获取构造器对象
Constructor<?> con1 = c1.getConstructor(String.class,int.class);
//创建对象
con1.newInstance("张三",26);
//第二种:获取字节码文件对象
Class<Person> c2 = Person.class;
//获取构造器对象
Constructor<Person> con2 = c2.getConstructor(String.class,int.class);
//创建对象
con2.newInstance("李四",25);
}
}
//用来测试反射的类
class Person
{
private String name;
private int age;
public Person(){};
public Person(String name,int age)
{
this.name = name;
this.age = age;
System.out.println(name+"****"+age);
}
} |