java反射系列四之创建运行时类的对象

一.概念认知


二.代码示例

package reflect;

public class TestConstructor {
    public static void main(String[] args) throws Exception {
        TestConstructor T = new TestConstructor();
        T.test();
    }
    public void test() throws Exception{
        String className = "reflect.Person";
        Class clazz = Class.forName(className);
        //创建对应的运行时类的对象,使用newInstance().实际上就是调用了运行时类的空参构造器
        //要想创建成功,1.要求对应的运行时类要有空参的构造器2.构造器的权限修饰符的权限要足够
        Object obj = clazz.newInstance();
        Person p = (Person)obj;
        System.out.println(p);
    }
}

猜你喜欢

转载自www.cnblogs.com/zjm1999/p/10336216.html
今日推荐