创建运行时类的对象
package Reflection1;
public class Person
{
package Reflection1;
import java.util.Random;
/*
通过反射创建对对应的运行时类的对象
*/
public class NewInstsanceTest {
public void test1() throws Exception {//右边获取实例的方式
Class<Person> claee = Person.class;
/*
newInstance(): 调用此方法,创建应的运行时类的对象,内部调用了运行时类的空参构造器
要想此方法正常的创建运行时类的对象,要求:
1. 运行时类必须提供空参的构造器
2. 空参构造器的访问权限得够,通常,设置为public
通常在javabean中要求提供一个pubilc的空参构造器,原因:
1. 便于通过反射,创建运行时类的对象
2. 便于子类继承此运行时类时,默认调用super()时,保证父类有此构造器
*/
Person obj = claee.newInstance();//
System.out.println(obj);
}
//体会反射的动态性
public void test2() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
for (int i=0;i<100;i++)
{
int num= new Random().nextInt(3);//0 1 2
String classPath="";
switch (num)
{
case 0:
classPath="java.util.Date";
break;
case 1:
classPath="java.lang.Object";
break;
case 2:
classPath="Reflection1.Person";
break;
}
Object obj=getInstance(classPath);
System.out.println(obj);
}
}
/*
创建一个指定类的对象
classPath:指定类的全类名
*/
public Object getInstance(String classPath) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
Class clzz = Class.forName(classPath);
//Class.forName("Reflection1.Person");
return clzz.newInstance();
}
public static void main(String[] args) throws Exception {
// new NewInstsanceTest().test1();
new NewInstsanceTest().test2();
}
}
浙公网安备 33010602011771号