前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >用反射获取构造方法 Constructor类

用反射获取构造方法 Constructor类

作者头像
用户2965768
发布2019-03-15 16:21:26
5690
发布2019-03-15 16:21:26
举报
文章被收录于专栏:wym

样例代码:

先创建一个类

代码语言:javascript
复制
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 + "]";
	}
	
}
代码语言:javascript
复制
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();
		}
	}
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019年03月11日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档