标签:
package com.czj;
public class Person {
String str= "string";
public Person() {
System.out.println("person 空构造函数");
}
public Person(String str ) {
System.out.println("person 带string造函数");
}
}
package com.czj;
import java.lang.reflect.Constructor;
public class Demo {
/*
* 反射机制, 创建类的对象; 获取类里面的 属性;方法;构造函数;
*/
public void test() throws Exception{
//1
Class class1=Class.forName("com.czj.Person");
//2
Class class2=Person.class;
//3
Class class3=new Person().getClass();
}
public void run() throws Exception{
Class clazz=Class.forName("com.czj.Person");
Constructor e= clazz.getConstructor(null);//调用为空的够早函数; 如果有参数的就把null改为属性值;
Person p=(Person) e.newInstance(null);//返回一个object对象所以要强制转换;
System.out.println(p.str);
}
public static void main(String []args) throws Exception{
Demo demo=new Demo();
demo.run();
}
}
标签:
原文地址:http://www.cnblogs.com/JohnChen-happy/p/4337086.html