反射(學習整理)----操作類、屬性、方法!


   剛學的反射,利用博客寫一篇筆記!(附上代碼!)

1、下面是我的分析筆記

其他:
    1、用static修飾的歸位類所擁有的,沒有static修飾的歸對象擁有!
    
    2、




反射機制:
    不需要用到new,反射不需要new!

    反射是程序運行的時候動態地加載類的屬性和方法
    
    獲取類對象類型中的內容,都必須通過classType對象
    步驟:
          1、獲取類的對象類型

            語法格式:    
                Class cls=Class.forName("包名.類名");
            舉例:
                Class<?> classType=Class.forName("cn.jason.reflections.Constomer");
            說明:
                此處的?代表任意類型對象,相當於Object

          2、通過反射,獲取類對象里面的所有屬性

            語法格式:
                Field[] fields=classType.getDeclaredFields();

                //循環打印獲取到的屬性Name
                for (Field field : fields) {
                    System.out.println(field.getName());
                }
          3、通過反射,獲取類對象里面的所有方法或指定的方法
            
            1)、獲取所有的方法
                //獲取類中的所有的方法
                Method[] methods=classType.getMethods();
                for (Method method : methods) {
                    System.err.println(method.getName());
                }

            2)、獲取指定方法名稱的方法

                //屬性的第一個字母截取出來,並且大寫化
                String firstLetter=name.substring(0, 1).toUpperCase();
                
                //拼接屬性get方法的方法名
                String getMethodName="get"+firstLetter+name.substring(1);
                String setMethodName="set"+firstLetter+name.substring(1);
        
                //現在動態獲取get方法
                    Method getmethod=classType.getDeclaredMethod(getMethodName, new Class[]{});
                
                //現在動態獲取set方法   參數列表:(int id)
                    Method setmethod=classType.getDeclaredMethod(setMethodName, new Class[]{field.getType()});
            
        分析說明一下:
            (1)getDeclaredMethod(getMethodName, new Class[]{});
                
                該方法的第一個參數,是需要獲取方法對象的方法名,

                該方法的第二個參數,是執行方法的參數類別的, 的參數類型的數組

            (2)getDeclaredMethod(setMethodName, new Class[]{field.getType()});

                 其中的field.getType()是獲取類字段的類型
        
            (3反射程序中,關於參數類型的對象數組:用Class[]{}存放
                       具體的數據類型:用int.class、String.class等形式
                       提示:Integer.TYPE 效果等價於 int.class
        
        
        4、通過反射,獲取類對象(要執行反射的獲取的方法,前提就是要獲取類的對象,但不是new出來的,是反射獲取得到的!//通過反射來創建對象:等同於Constomer c=new Constomer(001,"Jason"):構造器-----這里的目的是獲取類的對象(反射的形式獲取)
                    Object obj=classType.getConstructor(new Class[]{int.class,String.class})
                                        .newInstance(new Object[]{18,"天使彥"});    

            分析一下:
                1)、這個方法是使用反射機制獲取類的對象的,類似new出來的實例!

                2)、其中:getConstructor(new Class[]{int.class,String.class})
                       
                       說明:參數列表放的是:構造方法的參數列表的數據類型、或數據類型的集合

        
        5、執行方法---是否有返回值  根據方法的返回類型來確定    
            
            語法格式:    
                方法對象.invoke(類對象,實參數據集合)
                
            舉例:
                setmethod.invoke(obj,(new Object[]{18,"天使彥"});
            
                Object value=getmethod.invoke(obj,(new Object[]{});
        
            說明一下:
                實參數據集合:放在Object[]中,畢竟是參數據是可以為各種類型的!

  2、下面是測試源碼

實體類: 

 1 package cn.jason.reflections;
 2 
 3 /**
 4  * 反射測試:
 5  *         用戶類
 6  *    Created by Jason  2016-7-16  上午11:22:03
 7  */
 8 public class Constomer {
 9 
10     /**
11      * 成員變量
12      */
13     private int id;            //用戶id
14     private String name;    //用戶姓名
15     
16     /**
17      *構造器:
18      */
19     public Constomer(){
20         
21     }
22     public Constomer(int id,String name){
23         this.id=id;
24         this.name=name;
25     }
26     
27     /**
28      * getter和setter方法
29      */
30     public int getId() {
31         return id;
32     }
33     public void setId(int id) {
34         this.id = id;
35     }
36     public String getName() {
37         return name;
38     }
39     public void setName(String name) {
40         this.name = name;
41     }
42     
43     
44 }

  反射測試類:

 1 package cn.jason.reflections;
 2 
 3 import java.lang.reflect.Constructor;
 4 import java.lang.reflect.Field;
 5 import java.lang.reflect.Method;
 6 
 7 /**
 8  *    Created by Jason  2016-7-16  上午11:31:04
 9  */
10 public class TestReflect {
11     
12     public static void main(String[] args) {
13         TestReflect.getproperty();
14     }
15 
16     /**
17      * 獲取用戶類型里面的屬性以及getter好getter方法
18      */
19     public static void getproperty(){
20          try {
21             //第一步:獲取對象類型
22             Class<?> classType=Class.forName("cn.jason.reflections.Constomer");
23             
24             //通過反射,獲取用戶類里面的所有屬性
25             Field[] fields=classType.getDeclaredFields();
26             
27             //循環打印獲取到的屬性Name
28             int i=0;
29             for (Field field : fields) {
30                 String name=field.getName();
31                 //System.out.println("類對象的字段名稱:"+name);
32                 
33                 //屬性的第一個字母截取出來,並且大寫化
34                 String firstLetter=name.substring(0, 1).toUpperCase();
35                 
36                 //拼接屬性get方法的方法名
37                 String getMethodName="get"+firstLetter+name.substring(1);
38                 String setMethodName="set"+firstLetter+name.substring(1);
39                 //System.err.println("拼接后的方法名稱:"+getMethodName+","+setMethodName);
40                 
41                 //現在動態獲取get方法
42                     Method getmethod=classType.getDeclaredMethod(getMethodName, new Class[]{});
43                 
44                 //現在動態獲取set方法   參數列表:(int id)
45                     Method setmethod=classType.getDeclaredMethod(setMethodName, new Class[]{field.getType()});
46                     
47                 //通過反射來創建對象:等同於Constomer c=new Constomer(001,"Jason"):構造器-----這里的目的是獲取類的對象(反射的形式獲取)
48                     Object obj=classType.getConstructor(
49                                             new Class[]{int.class,String.class}).newInstance(
50                                             new Object[]{18,"天使彥"});
51                 //執行get方法獲取數據        空參數
52                     Object value=getmethod.invoke(obj, new Object[]{});
53             
54                     System.out.println("[1]執行了方法"+getMethodName+"()之后,返回結果是:"+value);
55                     
56                 //執行set方法:2次遍歷的參數類型是不一樣的!所以不能寫死了!否則會報參數類型錯誤!
57                     Object[] params=new Object[1];
58                     if(i==0){
59                         params[0]=22;
60                     }else{
61                         params[0]="Jason";
62                     }
63                     setmethod.invoke(obj, params);
64                     Object value2=getmethod.invoke(obj, new Object[]{});                    
65                     System.out.println("[2]執行了方法"+getMethodName+"()之后,返回結果是:"+value2);
66                     
67                     //計數器+1
68                     i++;
69             }
70             
71             //獲取類中的所有的方法
72             Method[] methods=classType.getMethods();
73             for (Method method : methods) {
74                 //System.err.println(method.getName());
75             }
76             
77         } catch (Exception e) {
78             e.printStackTrace();
79         }
80     }
81 }

  測試運行結果: 

[1]執行了方法getId()之后,返回結果是:18
[2]執行了方法getId()之后,返回結果是:22
[1]執行了方法getName()之后,返回結果是:天使彥
[2]執行了方法getName()之后,返回結果是:Jason
下面是獲取反射對象內部全部的方法
getName()
getId()
setName()
setId()
wait()
wait()
wait()
hashCode()
getClass()
equals()
toString()
notify()
notifyAll()

 


免責聲明!

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



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