反射-访问构造方法

创建一个类:

public class Example_01 {
	String s;
	int i,i2,i3;
	private Example_01(){
		
	}
	protected Example_01(String s,int i){
		this.s = s;
		this.i = i;
	}
	public Example_01(String...strings)throws NumberFormatException{
		if(0< strings.length)
			i = Integer.valueOf(strings[0]);
		if(0< strings.length)
			i2 = Integer.valueOf(strings[1]);
		if(0< 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);
	}

}

编写测试类:

public class Text{
	
	public static void main(String args[]){
		Example_01 example = new Example_01();
		Class exampleC = example.getClass();
		Constructor[] declaredConstructors = exampleC.getDeclaredConstructors();
		for (int i = 0; i < declaredConstructors.length; i++) {
			Constructor constructor = declaredConstructors[i];
			System.out.println("查看是否允许带有可变数量的参数:" + constructor.isVarArgs());
			System.out.println("该构造方法的入口参数类型依次为:");
			Class[] parameterTypes = constructor.getParameterTypes();
			for (int j = 0; j < parameterTypes.length; j++) {
				System.out.println("" + parameterTypes[j]);
			}
			System.out.println("该构造方法可能抛出的异常类型为:");
			Class[] exceptionTypes = constructor.getExceptionTypes();
			for (int j = 0; j < exceptionTypes.length; j++) {
				System.out.println("" + exceptionTypes[j]);
			}
			Example_01 example2 = null;
			while (example2 == null) {
				try {
					if(i== 2){
						example2 = (Example_01)constructor.newInstance();
					}else if(i == 1){
						example2 = (Example_01)constructor.newInstance("7",5);
					}else{
						Object[] parameters = new Object[]{new String[]{"100","200","300"}};
						example2 = (Example_01) constructor.newInstance(parameters);
					}
				} catch (Exception e) {
					e.printStackTrace();
					System.out.println("在创建对象时抛出异常,下面执行setAccessible()方法");
					constructor.setAccessible(true);
				}
			}
			example2.print();
			System.out.println();
		}
	}
}

输出效果:


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值