package set;
public class Person {
private String name;
private int age;// 创建构造方法,在new时就给属性传值
public Person(){
}
public Person(String name,int age){
this.name = name;
this.age = age;}
@Override
public String toString(){
return this.name +"\t"+ this.age;}}
package test0812;
import java.lang.reflect.Constructor;//使用java反射获取类的对象(调用有参构造方法创建实例对象)
public class Test04 {
public voidcreateObj(String className){
// 通过java反射获取B类的对象
try {
Class clazz = Class.forName(className);//获取有参构造方法(Constructor就是构造方法)
Constructor cons = clazz.getConstructor(new Class[]{
String.class,int.class});// 使用java反射获取类的对象
Object obj = cons.newInstance(new Object[]{
"张三",22});
System.out.println(obj);//张三 22} catch (Exception e){
e.printStackTrace();}}
public staticvoidmain(String[] args){
Test04 t = new Test04();
t.createObj("test0812.Person");}}