溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Java反射機制是什么及怎么實現(xiàn)

發(fā)布時間:2022-08-27 14:37:41 來源:億速云 閱讀:126 作者:iii 欄目:開發(fā)技術(shù)

本篇內(nèi)容主要講解“Java反射機制是什么及怎么實現(xiàn)”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“Java反射機制是什么及怎么實現(xiàn)”吧!

1.通過反射,我們可以構(gòu)建實例,得到成員變量的值,得到方法并調(diào)用。

還可以獲得定義在成員變量、方法、方法參數(shù)上的注解。

接下來看代碼實現(xiàn),然后講原理。

1)構(gòu)建無參實例:通過反射調(diào)用無參構(gòu)造函數(shù)

        //1.通過全類名加載字節(jié)碼對象
        Class clazz = Class.forName("com.example.lib.Person");
        //2.通過類的字節(jié)碼拿到定義的構(gòu)造函數(shù)
        Constructor constructor = clazz.getConstructor();
        //3.通過構(gòu)造方法創(chuàng)建對象
        Object obj = constructor.newInstance();

2)構(gòu)建有參數(shù)實例:

        //1.通過全類名加載字節(jié)碼對象
        Class clazz = Class.forName("com.example.lib.Person");
        //2.通過類的字節(jié)碼拿到定義的構(gòu)造函數(shù)
        Constructor constructor = clazz.getConstructor(int.class,String.class);
        //3.通過構(gòu)造方法創(chuàng)建對象
        Object obj = constructor.newInstance(20,"xiaohua");

3)通過反射獲取成員變量的值。

        //4.通過屬性名獲取屬性
        Field field = clazz.getDeclaredField("age");
        field.setAccessible(true);
        //5.調(diào)用get方法拿到對象obj屬性age的值
        Integer age = (Integer) field.get(obj);

4)通過反射調(diào)用對象的方法。

        //4.通過方法名和參數(shù)類型,拿到方法
        method = clazz.getMethod("setAge", int.class);
        //5.調(diào)用方法 obj是哪個對象身上的方法。
        method.invoke(obj, 21);
        method =  clazz.getMethod("getAge");
        method.invoke(obj);

5).通過反射獲取靜態(tài)變量的值。

       //1.通過全類名加載字節(jié)碼對象
        Class clazz = Class.forName("com.example.lib.Person");
        //2.獲取靜態(tài)屬性ID
        Field  field = clazz.getField("ID");
        field.setAccessible(true);
        //3.拿到靜態(tài)屬性ID的值。
        // 因為靜態(tài)變量存在方法區(qū),在對象創(chuàng)建之前,就已經(jīng)加裝到了內(nèi)存
        //所以,沒有對象,也可以獲取變量的值,這里傳null也是可以的。
        int id = (int) field.get(null);

2.通過反射獲取定義的注解的值

1)獲取成員變量的注解以及值。

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface BindView {
    int value();
}
public class MainActivity {
    @BindView(10000)
    TextView textView;
}
        //10通過反射拿到定義在屬性上的注解
        Class  clazz = MainActivity.class;
        Field textView = clazz.getDeclaredField("textView");
        BindView bindView = textView.getAnnotation(BindView.class);
        int txtId = bindView.value();

3)通過反射獲取定義在方法和方法參數(shù)上的注解以及值

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Post {
    String value() default "";
}
public interface NetWorkInterface {
    @Post("http://www.baidu.com")
    Call getPerson(@Queue("name") String name, @Queue("200") int price);
}
      //11通過反射拿到方法上定義的注解
        clazz = NetWorkInterface.class;
        Method method = clazz.getMethod("getPerson", String.class, int.class);
        //獲取Post注解
        Post post = method.getAnnotation(Post.class);
        //獲取值
        String url = post.value();
         //12通過反射拿到參數(shù)上的注解
        //為是個二維數(shù)組,因為方法參數(shù)會有多個,一個參數(shù)有可能定義多個注解
        Annotation[][] annotations = method.getParameterAnnotations();
        for (Annotation[] ans : annotations) {
            for (Annotation an : ans) {
                if (an instanceof Queue) {
                    Queue queue = (Queue) an;
                    String value = queue.value();
                }
            }
        }

4)獲取方法的參數(shù)和返回值類型。

        //13.拿到方法參數(shù)的類型。
        Type[] types = method.getGenericParameterTypes();
        for (Type type : types) {
            System.out.println(type.toString());
        }
        //14.獲取方法返回值類型
        Type type = method.getGenericReturnType();

3總結(jié):通過反射,可以拿到對象身上的成員變量的值、調(diào)用方法,獲取定義在成員變量、方法和 方法參數(shù)上的注解。Retrofit 就用到了注解加反射技術(shù),和動態(tài)代理(這個技術(shù)稍后分享)

4.通過反射,可以做到以上事情。反射的原理是啥?

1)我們寫的源代碼是.java文件,通過javac編譯后成為.class文件,即字節(jié)碼文件。

2)程序執(zhí)行時,JVM會類加載字節(jié)碼文件到內(nèi)存,嚴格意義上說是加載到方法區(qū),并轉(zhuǎn)換成

java.lang.Class對象。萬事萬物皆對象,Class被稱為類對象,描述類在元數(shù)據(jù)空間的數(shù)據(jù)結(jié)構(gòu),包含類中定義的屬性、方法、構(gòu)造方法、注解、接口等信息。

所有反射的第一步是拿到類對象Class對象。拿到了Class對象,也就拿到了類中定義的一切。

Class clazz = Class.forName("com.example.lib.Person");

這行代碼就是通過類加載器把Person類加載到內(nèi)存,并得到對應的Class 對象。

到此,相信大家對“Java反射機制是什么及怎么實現(xiàn)”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進入相關(guān)頻道進行查詢,關(guān)注我們,繼續(xù)學習!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI