java 反射 访问构造方法

来源:互联网 发布:网络水军怎么找 编辑:程序博客网 时间:2024/06/06 20:51
package com.fanshe.demo;public class Example_02 {String s;int i,i2,i3;private Example_02() {} protected Example_02(String s,int i){ this.s=s; this.i=i;  }   public Example_02(String...strings)throws NumberFormatException{if(0<strings.length){i=Integer.valueOf(strings[0]);}if(1<strings.length){i2=Integer.valueOf(strings[1]);}if(2<strings.length){i3=Integer.valueOf(strings[2]);}}public void print(){System.out.println("s="+s);System.out.println("i="+i);System.out.println("i2="+i2);System.out.println("i3="+i3);}}/////////////////////////////////////////////////////////////import java.lang.reflect.Constructor;public class Example_01 {/** * @param args */public static void main(String[] args) {Example_02 example_02=new Example_02("10","20","30");Class<? extends Example_02> class1=example_02.getClass();//获取所有权限public的类Constructor[] constructors=class1.getDeclaredConstructors();//获取所有public构造方法返回数组/* *遍历Constructor有哪些公共构造函数,能传传参数吗 */for (int i = 0; i < constructors.length; i++) {System.out.println("==============================\n"+ "===========================");//System.out.println(constructors[i]);//获取公共构造方法Constructor<?> constructor=constructors[i];//返回构造方法System.out.println("查看是否充许带有可变数量的参数: "+constructor.isVarArgs());/* * 获取构造方法里的参数并返回给Class类数组; * 因为返回的是一个类型所以用Class接收 */System.out.println("构造方法的入口参数类型为");Class[] classes= constructor.getParameterTypes();for (int j = 0; j < classes.length; j++) {System.out.println(classes[j]);}System.out.println("该构造方法可能抛出的异常为:");//获取所有抛出的异常类信息Class[] classes2=constructor.getExceptionTypes();for (int j = 0; j < classes2.length; j++) {System.out.println(j+""+classes2[j]);}Example_02 example_022=null;while (example_022==null) {try {//如果权限为私有就会异常if (i==2) {//充许默认构造方法创建对象//该构造方法  创建该构造方法的   声明类的新实例//每个构造方法生成的类example_022=(Example_02)constructor.newInstance();}else if(i==1){//充许带有参数的创建对象example_022=(Example_02)constructor.newInstance("7",5);}else {//Object[] objects=new Object[]{new String[]{"7","55","44","uf"}};example_022=(Example_02)constructor.newInstance(objects);}} catch (Exception e) {System.out.println("在创建对象时抛出异常,下面执行异常");constructor.setAccessible(true);}}if(example_022 !=null){example_022.print();System.out.println();}}}    }


原创粉丝点击