利用反射机制创建新类的两种方式及比较

来源:互联网 发布:渲染软件哪个好 编辑:程序博客网 时间:2024/05/19 15:41

【0】README

0.1) 本文描述+源代码均 转自 http://blog.csdn.net/fenglibing/article/details/4531033 , 旨在深入理解 如何利用反射机制创建类实例;
0.2) 转载的源代码,参见 https://github.com/pacosonTang/core-java-volume/tree/master/chapter5/reflectionCreateInstance


【1】通过反射创建新的类示例,有两种方式:

2.1)第一种方式: Class.newInstance()
2.2)第二种方式: Constructor.newInstance()


【2】以下对两种调用方式给以比较说明:

2.1)调用的构造函数有无参数: Class.newInstance() 只能够调用无参的构造函数,即默认的构造函数;而Constructor.newInstance() 可以根据传入的参数,调用任意构造函数(包括有参+无参);
2.2)是否抛出异常: Class.newInstance() 抛出所有由被调用构造函数抛出的异常;
2.3)调用的构造函数的可见性: Class.newInstance() 要求被调用的构造函数是可见的,也即必须是public类型的;而 Constructor.newInstance() 在特定的情况下,可以调用私有的构造函数(private);


【3】看个荔枝

3.1)A.java

package com.corejava.chapter5;public class A{    private A()    {        System.out.println("A's constructor is called.");    }    private A(int a, int b)    {        System.out.println("a:" + a + " b:" + b);    }}

3.2)B.java

package com.corejava.chapter5;import java.lang.reflect.Constructor;import static java.lang.System.out;public class B{    public static void main(String[] args)    {        B b;         b = new B();        out.println("通过Class.NewInstance()调用私有构造函数:");        b.newInstanceByClassNewInstance();        out.println("通过Constructor.newInstance()调用私有构造函数:");        b.newInstanceByConstructorNewInstance();    }    /* 通过Class.NewInstance()创建新的类示例 */    private void newInstanceByClassNewInstance()    {        try        {            /* 当前包名为reflect,必须使用全路径 */            A a = (A) Class.forName("com.corejava.chapter5.A").newInstance();        } catch (Exception e)        {            out.println("通过Class.NewInstance()调用私有构造函数【失败】");        }    }    /* 通过Constructor.newInstance()创建新的类示例 */    private void newInstanceByConstructorNewInstance()    {        try        {            /* 可以使用相对路径,同一个包中可以不用带包路径 */            Class c = Class.forName("com.corejava.chapter5.A");            /* 以下调用无参的、私有构造函数 */            Constructor c0 = c.getDeclaredConstructor();            c0.setAccessible(true);            A a0 = (A) c0.newInstance();            /* 以下调用带参的、私有构造函数 */            Constructor c1 = c.getDeclaredConstructor(new Class[] { int.class,int.class });            c1.setAccessible(true);            A a1 = (A) c1.newInstance(new Object[] { 5, 6 });        } catch (Exception e)        {            e.printStackTrace();        }    }}

这里写图片描述

0 0
原创粉丝点击