黑马程序员技术交流社区

标题: 构造方法反射的标准步骤 [打印本页]

作者: China_Riven    时间: 2015-7-20 16:59
标题: 构造方法反射的标准步骤
package cn.itcast;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/*
* 构造方法反射的标准步骤
*/
public class Demo4 {

        public static void main(String[] args) throws NoSuchMethodException,
                        SecurityException, InstantiationException, IllegalAccessException,
                        IllegalArgumentException, InvocationTargetException {

                // 1:获取字节码文件对象
                Class<Person> clazz = Person.class;

                // 2:获取指定的构造方法,这里选择空参的与三个参数的
                Constructor<Person> cfor0 = clazz.getConstructor();
                Constructor<Person> cfor3 = clazz.getDeclaredConstructor(String.class,
                                int.class, String.class);

                // 3:使用构造方法对象,创建对应的对象实例
                Person person = cfor0.newInstance();
                System.out.println(person);
               
                //因为3个参数的构造方法是私有化访问权限,外界无法访问,如果外界需要访问,则使用暴力反射,取消权限检查
                cfor3.setAccessible(true);
                Person person2 = cfor3.newInstance("唐嫣",18,"女");
                System.out.println(person2);
        }

}







欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2