反射中getConstructors与getDeclaredConstructors的区别
日期: 2020-11-24 分类: 跨站数据 414次阅读
1.反射中getConstructors与getDeclaredConstructors的区别?
区别是getConstructors只返回公共构造函数,而getDeclaredConstructors返回所有的构造函数(public,protected,default(package)access和private)
2.代码演示
//创建实体类
public class User {
private int age;
private String name;
public User(int age, String name) {
super();
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User() {
super();
}
}
public class Item {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
// TODO Auto-generated method stub
Method05();
}
private static void Method05() throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
//根据指定的文件路径返回一个Class对象
Class cls = Class.forName(“cn.yunhe.fanShe.User”);
//指定获取带有两个参数的构造器,要指定参类型、参数的位置、参数的个数
Constructor cons = cls.getConstructor(int.class,String.class);
// 通过这个构造器对象创建实体类对象
User user = (User)cons.newInstance(15,“嘻嘻”);
System.out.println(user);
}
public static void method03() throws ClassNotFoundException {
Class cls = Class.forName(“cn.yunhe.fanShe.User”);
//获取类中构造器
Constructor[] constructors = cls.getDeclaredConstructors();
for(Constructor constructor:constructors) {
System.out.println(constructor);
}
除特别声明,本站所有文章均为原创,如需转载请以超级链接形式注明出处:SmartCat's Blog
标签:java
上一篇: Java面试题大全(2021版)
精华推荐