JAVA 反射 示例

摘自 b站尚硅谷JAVA视频教程

 

Class personC = Person.class;

        //1 利用反射创建Person类
        Constructor cons = personC.getConstructor(String.class,int.class);
        Object obj = cons.newInstance("tom",12);
        Person p = (Person) obj;
        System.out.println(p);

        //2 通过反射,调用对象指定的属性
        Field age = personC.getDeclaredField("age");
        age.set(p, 10);
        System.out.println(p);

        // 3 通过反射调用方法
        Method show = personC.getDeclaredMethod("show");
        show.invoke(p);
        //4 通过反射可以调用私有的构造器

        Constructor con1 = personC.getDeclaredConstructor(String.class);
        con1.setAccessible(true);
        Object obj1 = con1.newInstance("Jerry");
        Person p1 =(Person) obj1;
        System.out.println(p1);

        //5 通过反射调用私有属性
        Field name = personC.getDeclaredField("name");
        name.setAccessible(true);
        name.set(p1,"Sam");
        System.out.println(p1);
        //6 调用私有方法
        Method showNation = personC.getDeclaredMethod("showNation", String.class);
        showNation.setAccessible(true);
        String nation = (String) showNation.invoke(p1,"中国");
        System.out.println(nation);

 

posted @ 2020-02-23 15:56  超级学渣渣  阅读(128)  评论(0编辑  收藏  举报