如何通过反射来创建对象?getConstructor()和getDeclaredConstructor()区别?
2016-07-19 21:15
417 查看
1. 通过类对象调用newInstance()方法,适用于无参构造方法:
例如:String.class.newInstance()
2. 通过类对象的getConstructor()或getDeclaredConstructor()方法获得构造器(Constructor)对象并调用其newInstance()方法创建对象,适用于无参和有参构造方法。
例如:String.class.getConstructor(String.class).newInstance("Hello");
********* getConstructor()和getDeclaredConstructor()区别:*********
getDeclaredConstructor(Class<?>... parameterTypes)
这个方法会返回制定参数类型的所有构造器,包括public的和非public的,当然也包括private的。
getDeclaredConstructors()的返回结果就没有参数类型的过滤了。
再来看getConstructor(Class<?>... parameterTypes)
这个方法返回的是上面那个方法返回结果的子集,只返回制定参数类型访问权限是public的构造器。
getConstructors()的返回结果同样也没有参数类型的过滤。
例如:String.class.newInstance()
public class Solution { public static void main(String[] args) throws Exception { Solution solution = Solution.class.newInstance(); Solution solution2 = solution.getClass().newInstance(); Class solutionClass = Class.forName("Solution"); Solution solution3 = (Solution) solutionClass.newInstance(); System.out.println(solution instanceof Solution); //true System.out.println(solution2 instanceof Solution); //true System.out.println(solution3 instanceof Solution); //true } }
2. 通过类对象的getConstructor()或getDeclaredConstructor()方法获得构造器(Constructor)对象并调用其newInstance()方法创建对象,适用于无参和有参构造方法。
例如:String.class.getConstructor(String.class).newInstance("Hello");
public class Solution { private String str; private int num; public Solution() { } public Solution(String str, int num) { this.str = str; this.num = num; } public Solution(String str) { this.str = str; } public static void main(String[] args) throws Exception { Class[] classes = new Class[] { String.class, int.class }; Solution solution = Solution.class.getConstructor(classes).newInstance("hello1", 10); System.out.println(solution.str); // hello1 Solution solution2 = solution.getClass().getDeclaredConstructor(String.class).newInstance("hello2"); System.out.println(solution2.str); // hello2 Solution solution3 = (Solution) Class.forName("Solution").getConstructor().newInstance(); // 无参也可用getConstructor() System.out.println(solution3 instanceof Solution); // true } }
********* getConstructor()和getDeclaredConstructor()区别:*********
getDeclaredConstructor(Class<?>... parameterTypes)
这个方法会返回制定参数类型的所有构造器,包括public的和非public的,当然也包括private的。
getDeclaredConstructors()的返回结果就没有参数类型的过滤了。
再来看getConstructor(Class<?>... parameterTypes)
这个方法返回的是上面那个方法返回结果的子集,只返回制定参数类型访问权限是public的构造器。
getConstructors()的返回结果同样也没有参数类型的过滤。
相关文章推荐
- Spring数据源Spring数据源配置之JDBC
- Windows系统学快捷键
- NOIPの模拟_2016_7_19_t1_腐败
- emmet精简笔记【笔记】
- 解密 Uber 数据团队的基础数据架构优化之路
- android MVP 架构思路
- 题目1070:今年的第几天?
- caffe的python接口学习(8):caffemodel中的参数及特征的抽取
- Windows下VC++显示UTF-8编码中文
- Python操作memecache
- unix:fork()函数进阶讲解
- jboss eap 6.2 ear包 下使用log4j日志
- Sublime Text插件之Emmet
- SharedPreferences缓存
- Linux VMnet Adapter无法启动的解决办法
- 使用url获取网络资源
- Centos7.2配置yum源
- Hadoop3.0新特性
- 【小松教你手游开发】【系统模块开发】根据上一个GameObject坐标生成的tips界面
- 文件路径和文件读取方