Young87

SmartCat's Blog

So happy to code my life!

游戏开发交流QQ群号60398951

当前位置:首页 >跨站数据

反射中getConstructors与getDeclaredConstructors的区别

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面试题大全(2021版)

下一篇: 「硬见小百科」缩短PCB设计时间,要掌握技巧

精华推荐