反射机制中获取类中的构造器
getDeclaredConstructor()和getConstructor()区别及其用法如下
(创建的测试实体类在最后)
1.获取类指定的构造器:getDeclaredConstructor()
1.1默认不传参数,获取无参构造器
Po po = new Po();
Class c1 = po.getClass();
//获取无参构造
Constructor constructors1;
try {
constructors1 = c1.getDeclaredConstructor();
System.out.println(Modifier.toString(constructors1.getModifiers()));
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
获取无参的构造器
1.2获取指定类型的构造器
//取有两个参数分别为int和String类型的构造方法
Class[] p = {int.class,String.class};
try {
constructors1=c1.getDeclaredConstructor(p);
System.out.println(Modifier.toString(constructors1.getModifiers()));
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
1.3.获取所有构造器:getDeclaredConstructors()
Constructor[] constructors;//创建一个构造器的数组
constructors=c1.getDeclaredConstructors();//获取所有的构造器存到上面第一好的数组当中
for (int i = 0; i < constructors.length; i++) {
//循环输出获得的构造器数组的权限修饰符
System.out.println(Modifier.toString(constructors[i].getModifiers())+":修饰符" );
}
结果如下:
2.getConstructor()(和上面的getDeclaredConstructor()方法相同,区别是只返回public修饰符的构造器)
2.1默认获取无参构造器(不指定参数)
Constructor constructor;
try {
//返回无参的构造器
constructor=c1.getConstructor();
System.out.println(Modifier.toString(constructor.getModifiers()));//public
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
2.2指定参数回去其构造器
//取有两个参数分别为int和String类型的构造方法
Class[] p = {int.class,String.class};
try {
constructors1=c1.getConstructor(p);
System.out.println(Modifier.toString(constructors1.getModifiers()));
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
注意:如果把指定参数的构造器权限修饰符改成不是public会报错,只会获取public修饰符的构造器
private Po(int age, String name) {
super();
this.age = age;
this.name = name;
}
2.3获取全部构造器getConstructors()
注意:只获得public修饰符的构造器
Constructor[] constructors;//创建一个构造器的数组
constructors=c1.getConstructors();//获取所有的构造器存到上面第一好的数组当中
for (int i = 0; i < constructors.length; i++) {
//循环输出获得的构造器数组的权限修饰符
System.out.println(Modifier.toString(constructors[i].getModifiers())+":修饰符" );
}
4.po实体类
public class Po {
private int age;
private String name;
private int testint;
public Po(int age) {
super();
this.age = age;
}
private Po(String name) {
super();
this.name = name;
}
private Po(int age, String name) {
super();
this.age = age;
this.name = name;
}
public Po(){
}
}