用反射获取构造方法 Constructor类

样例代码:

先创建一个类



public class DEmo {

	int id;
	String name;
	double val;
	public DEmo() {
		super();
	}
	public DEmo(int id) {
		super();
		this.id = id;
	}
	private DEmo(int id, String name, double val) {
		super();
		this.id = id;
		this.name = name;
		this.val = val;
	}
	@Override
	public String toString() {
		return "DEmo [id=" + id + ", name=" + name + ", val=" + val + "]";
	}
	
}
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;

public class Text {

	 
	public static void main(String[] a){
		try {
			Class class1 = Class.forName("DEmo");
			Constructor[] c = class1.getDeclaredConstructors();//获取所有构造方法
			for(Constructor con:c)
			{
				System.out.print(Modifier.toString(con.getModifiers())+ " ");//修饰符
				System.out.print(con.getName() + "("); //方法名
				Class class2[] = con.getParameterTypes();  //获取参数
				for(int i = 0;i<class2.length; i++){
					System.out.print(class2[i].getSimpleName()+" args ");
					if(i!=class2.length-1)System.out.print(",");
					
				}
				System.out.print("){}\n");
			}
			Constructor cs1 = class1.getDeclaredConstructor();//无参构造
			Object obj = cs1.newInstance();//
			System.out.println(obj.toString());
			
			Constructor cs2 = class1.getConstructor(int.class);
			obj = cs2.newInstance(123);
			System.out.println(obj.toString());
			
			Constructor cs3 = class1.getDeclaredConstructor(int.class, String.class, double.class);
			cs3.setAccessible(true);//获取操作权限
			obj = cs3.newInstance(123, "反射", 2.2);
			System.out.println(obj.toString());
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wym_king

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值