用反射获取构造方法 Constructor类

2019-03-15 16:21:26 浏览数 (1)

样例代码:

先创建一个类

代码语言: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();
		}
	}
}

0 人点赞