如何通過反射來創建對象?getConstructor()和getDeclaredConstructor()區別?


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");

 

 1 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 }

 

 

 

********* getConstructor()和getDeclaredConstructor()區別:*********

getDeclaredConstructor(Class<?>... parameterTypes) 
這個方法會返回制定參數類型的所有構造器,包括public的和非public的當然也包括private的。
getDeclaredConstructors()的返回結果就沒有參數類型的過濾了。

再來看getConstructor(Class<?>... parameterTypes)
這個方法返回的是上面那個方法返回結果的子集,只返回制定參數類型訪問權限是public的構造器。
getConstructors()的返回結果同樣也沒有參數類型的過濾。
 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM