方法介绍
方法名 | 描述 |
getDeclaredConstructors() | 返回Constructor对象的一个数组,这些对象反映此Class对象表示的类声明的所有构造方法 |
getConstructors() | 返回一个包含某些Constructor对象的数组,这些对象反映此Class对象所表示的类的所有公共(public)构造方法 |
getConstructor(Class<?>...parameterTypes) | 返回一个Constructor对象,它反映此Class对象所表示的类的指定公共(public)构造方法 |
getDeclaredConstructor(Class<?>...parameterTypes) | 返回一个Constructor对象,该对象反映此Class对象所表示的类或接口的指定构造方法 |
方法使用
修改Users类
public class Users {
private String username;
private int userage;
public Users(){
}
public Users(String username,int userage){
this.username = username;
this.userage = userage;
}
public Users(String username){
this.username = username;
}
public Users(int userage){
this.userage = userage;
}
public String getUsername(){
return username;
}
public void setUsername(String username){
this.username = username;
}
public int getUserage(){
return userage;
}
public void setUserage(int userage){
this.userage = userage;
}
}
获取构造方法
public class GetConstructor {
public static void main(String[] args)throws Exception{
Class clazz = Users.class;
Constructor[] arr = clazz.getDeclaredConstructors();
for(Constructor c : arr){
System.out.println(c);
}
System.out.println("------------------------------");
Constructor[] arr1 = clazz.getConstructors();
for(Constructor c : arr){
System.out.println(c);
}
System.out.println("------------------------------");
Constructor c = clazz.getDeclaredConstructor(int.class);
System.out.println(c);
System.out.println("------------------------------");
Constructor c1 = clazz.getConstructor(null);
System.out.println(c1);
}
}
通过构造方法创建对象
public class GetConstructor2 {
public static void main(String[] args)throws Exception{
Class clazz = Users.class;
Constructor constructor = clazz.getConstructor(String.class,int.class);
Object o = constructor.newInstance("abc",18);
Users users = (Users)o;
System.out.println(users.getUsername()+"\t"+users.getUserage());
}
}