java通过字节对象可以获取class类中的构造函数,以下三种分别为获取无参的构造函数、公有的构造函数和私有的构造函数。
people对象的代码如下:
public class People {
private String name;
private String sex;
private int age;
public People(){
System.out.println("构造方法被调用了啊!");
}
public People(String name){
this.name=name;
System.out.println("构造方法被调用了啊!+String");
}
public People(int age){
this.age=age;
System.out.println("构造方法被调用了啊!+int");
}
private People(String name,String sex){
this.name=name;
this.sex=sex;
System.out.println("构造方法被调用了啊!+name +sex");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
获取构造函数的方法如下:
public class ConstructorGetDemo {
/**
* 获取无参数的构造函数
*/
@Test
public void test1() throws Exception{
//通过类获取class对象
Class clazz1= Class.forName("com.wzd.tool.People");
//获取只有一个无参的构造器
Constructor<People> constructor=clazz1.getConstructor(null);
//实例化构造器
People people=constructor.newInstance();
//打印people对象的名字
System.out.println(people.getName());
}
/**
* 获取有参的共有的构造函数
*/
@Test
public void test2() throws Exception{
//通过类获取class对象
Class<People> clazz1=People.class;
//获取只有一个String参数的构造器
Constructor<People> constructor=clazz1.getConstructor(String.class);
//传入String值实例化构造器
People people=constructor.newInstance("张三");
//打印people对象的名字
System.out.println(people.getName());
}
/**
* 获取私有的构造函数
*/
@Test
public void test3() throws Exception{
//通过类获取class对象
Class<People> clazz1=People.class;
//获取只有一个String参数的构造器
Constructor<People> constructor=clazz1.getDeclaredConstructor(String.class,String.class);
//设置可以访问私有的构造函数
constructor.setAccessible(true);
//传入String值实例化构造器
People people=constructor.newInstance("张三","男");
//打印people对象的名字
System.out.println("姓名:"+people.getName());
System.out.println("性别:"+people.getSex());
}
}