java通過反射獲取調用變量以及方法


一:反射概念

可以通過Class類獲取某個類的成員變量以及方法,並且調用之。

 

二:通過反射獲取方法、變量、構造方法

 

 1 @Test
 2     // 通過反射獲取類定義的方法
 3     public void testMethod() throws Exception {
 4         @SuppressWarnings("rawtypes")
 5         Class clazz = Class.forName("java.lang.String");
 6         Method[] m = clazz.getDeclaredMethods();
 7         for (int i = 0; i < m.length; i++) {
 8             System.out.println(m[i].getName() + " " + m[i].getDeclaringClass());
 9         }
10     }
11 
12     @Test
13     // 通過反射獲取類定義的變量
14     public void testField() throws Exception {
15         @SuppressWarnings("rawtypes")
16         Class clazz = Class.forName("java.lang.String");
17         Field[] fields = clazz.getFields();
18         for (Field f : fields) {
19             System.out.println(f.getName());
20         }
21     }
22 
23     @Test
24     // 通過反射獲取類定義的構造方法
25     public void testConstructor() throws Exception {
26         @SuppressWarnings("rawtypes")
27         Class clazz = Class.forName("java.lang.String");
28         @SuppressWarnings("rawtypes")
29         Constructor[] cons = clazz.getConstructors();
30         for (@SuppressWarnings("rawtypes")
31         Constructor c : cons) {
32             System.out.println(c + " " + c.getDeclaringClass());
33         }
34     }

 

三:通過反射調用類定義的方法

 

 1 @Test
 2     // 通過反射調用類定義的方法
 3     public void testInvokeMethod() throws Exception {
 4         Class clazz = Class.forName("java.lang.String");
 5         // 定義參數類型
 6         Class[] params = new Class[1];
 7         params[0] = String.class;
 8         Method m = clazz.getDeclaredMethod("indexOf", params);
 9         // 設置參數
10         Object[] p = new Object[1];
11         p[0] = "e";
12         Integer s = (Integer) m.invoke("helloworld!", p);
13         System.out.println(s);
14     }

 


免責聲明!

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



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