反射的动态性

体会反射的动态性

package com.reflection;

import java.util.Random;

import org.junit.Test;

/**
 * 通过发射创建对应的运行时类的对象
 * 
 */
public class NewInstanceTest {

    @Test
    public void test1() throws IllegalAccessException, InstantiationException {

        Class<Person> clazz = Person.class;
        /**
         * newInstance():调用此方法,创建对应的运行时类的对象。内部调用了运行时类的空参的构造器
         * 
         * 要想此方法正常的创建运行时类的对象,要求:
         * 
         * 1.运行时类必须提供空参的构造器
         * 
         * 2.空参的构造器的访问权限得够。通常,设置为 public。
         * 
         * 在 javabean 中要求提供一个 public 的空参构造器。原因:
         * 
         * 1.便于通过反射,创建运行时类的对象
         * 
         * 2.便于子类继承此运行时类,默认调用 super() 时,保证父类有此构造器
         */

        Person obj = clazz.newInstance();
        System.out.println(obj);
    }

    // 体会反射的动态性
    @Test
    public void test2() {

        for (int i = 0; i < 100; i++) {
            // 0,1,2
            int num = new Random().nextInt(3);
            String classPath = "";
            switch (num) {
                case 0:
                    classPath = "java.util.Date";
                    break;
                case 1:
                    classPath = "java.lang.Object";
                    break;
                case 2:
                    classPath = "com.reflection.Person";
                    break;
            }

            Object obj = null;
            try {
                obj = getInstance(classPath);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(obj);
        }

    }

    /**
     * 创建一个指定类的对象。
     *
     * classPath:指定类的全类名
     */
    public Object getInstance(String classPath) throws Exception {
        Class clazz = Class.forName(classPath);
        return clazz.newInstance();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值