1. 通过类对象调用newInstance()方法,适用于无参构造方法:

例如: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()的返回结果同样也没有参数类型的过滤。

最新文章

  1. 实战:考虑性能--Solr索引的schema设计
  2. python之对指定目录文件夹的批量重命名
  3. MFC添加右键菜单
  4. tmux列表重命名
  5. Lambda表达式之Python
  6. 转:C语言字符串操作函数 - strcpy、strcmp、strcat、反转、回文
  7. Linux 下开放指定端口
  8. IOS开发之──应用之间调用(1)
  9. poj 1338 Ugly Numbers(丑数模拟)
  10. tomcat使用说明
  11. 在word中批量制作条形码
  12. 每天一个JavaScript实例-动态省份选择城市
  13. CoffeeScript NgComponent
  14. mysql、mariadb安装和多实例配置
  15. SQLserver学习(四)——T-SQL编程之事务、索引和视图
  16. Java 容器之Hashset 详解
  17. Cocos2D中的ObjectAL简介
  18. RedHat系列软件管理(第二版) --脚本安装
  19. 怎样在ASP.NET(C#) 使用Json序列化反序列化问题?
  20. c++与java的几个不同点

热门文章

  1. js node.children与node.childNodes与node.firstChild,node,lastChild之间的关系
  2. Javascript中的相等比较
  3. Java中使用File类删除文件夹和文件
  4. CTF中的AWD套路
  5. JS综合面试题1
  6. php 单例模式封装MySQL类
  7. MySql进行批量插入时的几种sql写法
  8. 路由网关--spring cloud zuul
  9. 注册Bean
  10. spark代码写入hdfs错误