Java开发之十二:getConstructor()和getDeclaredConstructor()区别

********* getConstructor()和getDeclaredConstructor()区别:*********

getDeclaredConstructor(Class<?>... parameterTypes) 
这个方法会返回制定参数类型的所有构造器,包括public的和非public的,当然也包括private的。
getDeclaredConstructors()的返回结果就没有参数类型的过滤了。

再来看getConstructor(Class<?>... parameterTypes)
这个方法返回的是上面那个方法返回结果的子集,只返回制定参数类型访问权限是public的构造器。
getConstructors()的返回结果同样也没有参数类型的过滤。

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

   例如:String.class.newInstance()

 1 public class Solution {
 2 
 3     public static void main(String[] args) throws Exception {
 4 
 5         Solution solution = Solution.class.newInstance();
 6 
 7         Solution solution2 = solution.getClass().newInstance();
 8 
 9         Class solutionClass = Class.forName("Solution");
10         Solution solution3 = (Solution) solutionClass.newInstance();
11 
12         System.out.println(solution instanceof Solution); //true
13         System.out.println(solution2 instanceof Solution); //true
14         System.out.println(solution3 instanceof Solution); //true
15     }
16     
18 }

2. 通过类对象的getConstructor()或getDeclaredConstructor()方法获得构造器(Constructor)对象并调用其newInstance()方法创建对象,适用于无参和有参构造方法。

   例如:String.class.getConstructor(String.class).newInstance("Hello");

public class Solution {
 2 
 3     private String str;
 4     private int num;
 5 
 6     public Solution() {
 7 
 8     }
 9 
10     public Solution(String str, int num) {
11         this.str = str;
12         this.num = num;
13     }
14 
15     public Solution(String str) {
16         this.str = str;
17     }
18 
19     public static void main(String[] args) throws Exception {
20 
21         Class[] classes = new Class[] { String.class, int.class };
22         Solution solution = Solution.class.getConstructor(classes).newInstance("hello1", 10);
23         System.out.println(solution.str); // hello1
24 
25         Solution solution2 = solution.getClass().getDeclaredConstructor(String.class).newInstance("hello2");
26         System.out.println(solution2.str); // hello2
27 
28         Solution solution3 = (Solution) Class.forName("Solution").getConstructor().newInstance(); // 无参也可用getConstructor()
29         System.out.println(solution3 instanceof Solution); // true
30     }
31 
32 }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

隨意的風

如果你觉得有帮助,期待你的打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值