反射

Reflect

Java反射機制時在運行狀態(tài)中张肾,對于任意一個類管宵,都能知道這個類所有的屬性和方法截珍;對于任意一個對象,都能調(diào)用它的任意一個方法和屬性箩朴;這種動態(tài)獲取信息以及動態(tài)調(diào)用對象的方法的功能稱為Java語言的反射機制岗喉。(就是通過class文件對象,使用該文件中的成員變量炸庞、構(gòu)造方法钱床、成員方法)

獲取class文件對象(Class)

  • Object類中的getClass()方法
  • 數(shù)據(jù)類型的靜態(tài)屬性class
  • Class.forName("類路徑")
public class Student {
    private String name;
    Integer age;
    public String addr;

    public Student() {
    }

    public Student(String name, Integer age, String addr) {
        this.name = name;
        this.age = age;
        this.addr = addr;
    }

    private Student(String addr) {
        this.addr = addr;
    }

    public String method(String s) {
        return String.format("method_%s", s);
    }
  
  void show() {
        System.out.println("student show");
    }

    private void test() {
        System.out.println("student test ");
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", addr='" + addr + '\'' +
                '}';
    }
}
public class ReflectDemo {
    public static void main(String[] args) throws ClassNotFoundException {
        // Object類中的getClass()方法
        Student student = new Student();
        Class<? extends Student> aClass = student.getClass();

        // 數(shù)據(jù)類型的靜態(tài)屬性class
        Class<Student> bClass = Student.class;

        // Class.forName("類路徑")
        Class<?> cClass = Class.forName("com.net.reflect.Student");


        // 三種方式獲取的是同一個class文件對象
        // true
        System.out.println(aClass == bClass);
        // true
        System.out.println(bClass == cClass);
    }
}

獲取構(gòu)造方法并使用

public class ReflectDemo2 {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        // 獲取字節(jié)碼文件對象
        Class<Student> studentClass = Student.class;

        // 獲取所有公共構(gòu)造方法
        Constructor<?>[] constructors = studentClass.getConstructors();
        for (Constructor<?> constructor : constructors) {
            System.out.println(constructor);
        }

        // 獲取所有構(gòu)造方法
        Constructor<?>[] declaredConstructors = studentClass.getDeclaredConstructors();
        for (Constructor<?> declaredConstructor : declaredConstructors) {
            System.out.println(declaredConstructor);
        }

        // 獲取指定構(gòu)造方法并使用
        Constructor<Student> declaredConstructor = studentClass.getDeclaredConstructor(String.class, Integer.class, String.class);
        System.out.println(declaredConstructor);
        // 創(chuàng)建實例
        Student student = declaredConstructor.newInstance("zhansan", 11, "aaa");
        System.out.println(student);

        // 獲取私有方法并使用
        Constructor<Student> con = studentClass.getDeclaredConstructor(String.class);
        // 設置訪問權(quán)限
        con.setAccessible(true);
        // 創(chuàng)建實例
        Student student1 = con.newInstance("bbb");
        System.out.println(student1);
    }
}

獲取成員變量并使用

public class ReflectField {
    public static void main(String[] args) throws NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        // 獲取字節(jié)碼文件對象
        Class<Student> studentClass = Student.class;

        // 獲取所有公開的成員變量
        // public java.lang.String com.net.mybatisplus.reflect.Student.addr
        Field[] fields = studentClass.getFields();
        for (Field field : fields) {
            System.out.println(field);
        }

        // 獲取所有成員變量
        // private java.lang.String com.net.mybatisplus.reflect.Student.name
        // java.lang.Integer com.net.mybatisplus.reflect.Student.age
        // public java.lang.String com.net.mybatisplus.reflect.Student.addr
        Field[] declaredFields = studentClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            System.out.println(declaredField);
        }

        // 獲取單個公開成員變量并對其賦值
        Constructor<Student> constructor = studentClass.getConstructor();
        Student student = constructor.newInstance();

        Field addr = studentClass.getField("addr");
        addr.set(student, "ccc");
        // Student{name='null', age=null, addr='ccc'}
        System.out.println(student);

        // 獲取單個私有成員變量并對其賦值
        Field name = studentClass.getDeclaredField("name");
        name.setAccessible(true);
        name.set(student, "zhangsan");
        // Student{name='zhangsan', age=null, addr='ccc'}
        System.out.println(student);

    }
}

獲取成員方法并使用

public class ReflectMethod {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        // 獲取字節(jié)碼文件對象
        Class<Student> studentClass = Student.class;

        // 獲取所有公開方法(包括父類)
        Method[] methods = studentClass.getMethods();
        for (Method method : methods) {
            System.out.println(method);
        }
        System.out.println("-----------------");

        // 獲取所有方法(不包括父類)
        Method[] declaredMethods = studentClass.getDeclaredMethods();
        for (Method declaredMethod : declaredMethods) {
            System.out.println(declaredMethod);
        }
        System.out.println("-----------------");

        // 獲取單個公開方法并使用
        Constructor<Student> constructor = studentClass.getConstructor();
        Student student = constructor.newInstance();

        Method method = studentClass.getMethod("method", String.class);
        Object stuMethod = method.invoke(student, "stuMethod");
        System.out.println(stuMethod);
        System.out.println("-----------------");
        
        // 獲取單個私有方法并使用
        Method test = studentClass.getDeclaredMethod("test");
        test.setAccessible(true);
        test.invoke(student);
    }
}

工具類

public class ReflectTool {
    // 賦值對象的任意屬性
    public static void setProperty(Object obj, String propertyName, Object value)
            throws NoSuchFieldException, IllegalAccessException {
        
        // 獲取字節(jié)碼文件對象
        Class<?> aClass = obj.getClass();

        // 獲取成員變量
        Field declaredField = aClass.getDeclaredField(propertyName);

        // 取消訪問檢查
        declaredField.setAccessible(true);

        // 賦值
        declaredField.set(obj, value);
    }
}

反射越過泛型檢查

public class ListReflect {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        List<Integer> list = Lists.newArrayList();
        Class<? extends List> aClass = list.getClass();

        Method add = aClass.getDeclaredMethod("add", Object.class);

        add.setAccessible(true);
        add.invoke(list, "list1");
        add.invoke(list, 11);
        add.invoke(list, true);

        System.out.println(list);
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市埠居,隨后出現(xiàn)的幾起案子查牌,更是在濱河造成了極大的恐慌事期,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,204評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件纸颜,死亡現(xiàn)場離奇詭異兽泣,居然都是意外死亡,警方通過查閱死者的電腦和手機胁孙,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,091評論 3 395
  • 文/潘曉璐 我一進店門唠倦,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人涮较,你說我怎么就攤上這事稠鼻。” “怎么了狂票?”我有些...
    開封第一講書人閱讀 164,548評論 0 354
  • 文/不壞的土叔 我叫張陵候齿,是天一觀的道長。 經(jīng)常有香客問我苫亦,道長毛肋,這世上最難降的妖魔是什么怨咪? 我笑而不...
    開封第一講書人閱讀 58,657評論 1 293
  • 正文 為了忘掉前任屋剑,我火速辦了婚禮,結(jié)果婚禮上诗眨,老公的妹妹穿的比我還像新娘唉匾。我一直安慰自己,他們只是感情好匠楚,可當我...
    茶點故事閱讀 67,689評論 6 392
  • 文/花漫 我一把揭開白布巍膘。 她就那樣靜靜地躺著,像睡著了一般芋簿。 火紅的嫁衣襯著肌膚如雪峡懈。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,554評論 1 305
  • 那天与斤,我揣著相機與錄音肪康,去河邊找鬼。 笑死撩穿,一個胖子當著我的面吹牛磷支,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播食寡,決...
    沈念sama閱讀 40,302評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼雾狈,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了抵皱?” 一聲冷哼從身側(cè)響起善榛,我...
    開封第一講書人閱讀 39,216評論 0 276
  • 序言:老撾萬榮一對情侶失蹤辩蛋,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后锭弊,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體堪澎,經(jīng)...
    沈念sama閱讀 45,661評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,851評論 3 336
  • 正文 我和宋清朗相戀三年味滞,在試婚紗的時候發(fā)現(xiàn)自己被綠了樱蛤。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,977評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡剑鞍,死狀恐怖昨凡,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情蚁署,我是刑警寧澤腹侣,帶...
    沈念sama閱讀 35,697評論 5 347
  • 正文 年R本政府宣布,位于F島的核電站署咽,受9級特大地震影響自点,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜久妆,卻給世界環(huán)境...
    茶點故事閱讀 41,306評論 3 330
  • 文/蒙蒙 一晌杰、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧筷弦,春花似錦肋演、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,898評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至奸绷,卻和暖如春梗夸,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背号醉。 一陣腳步聲響...
    開封第一講書人閱讀 33,019評論 1 270
  • 我被黑心中介騙來泰國打工反症, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人扣癣。 一個月前我還...
    沈念sama閱讀 48,138評論 3 370
  • 正文 我出身青樓惰帽,卻偏偏與公主長得像,于是被迫代替她去往敵國和親父虑。 傳聞我的和親對象是個殘疾皇子该酗,可洞房花燭夜當晚...
    茶點故事閱讀 44,927評論 2 355