反射demo

反射类

/**
* @ClassName:StudentReflectTest
* @Description: TODO
* @author wxtang
* @Date: 2019/4/16 15:29
* @version 1.0.0
*
*/
public class StudentReflectTest {
private Stringname;
    private int age;
    private int price;
    public StringgetName() {
return name;
    }
public void setName(String name) {
this.name = name;
    }
public int getAge() {
return age;
    }
public void setAge(int age) {
this.age = age;
    }
public int getPrice() {
return price;
    }
public void setPrice(int price) {
this.price = price;
    }
public static void main(String[] args)throws Exception {
StudentReflectTest student =new StudentReflectTest();
        student.setName("小红");
        student.setAge(11);
        student.setPrice(175);
        System.out.println("学生姓名 :"+student.getName());
        System.out.println("学生年龄 :"+student.getAge());
        System.out.println("学生零花钱 :"+student.getPrice());
        //使用反射修改价格1
        Class clz = Class.forName("com.travelsky.adap.rescheduler.switchbin.StudentReflectTest");
        Method setPrice = clz.getMethod("setPrice",int.class);
        setPrice.setAccessible(true);
        Constructor con = clz.getConstructor();
        Object stuObj = con.newInstance();
        setPrice.invoke(stuObj,365);
        Method getPrice = clz.getMethod("getPrice");
        System.out.println("反射后的零花钱 :"+getPrice.invoke(stuObj));
        Method method = StudentReflectTest.class.getMethod("setAge", int.class);
        method.setAccessible(true);
        method.invoke(student,26);
        Method getAge = StudentReflectTest.class.getMethod("getAge");
        System.out.println("反射后的年龄 :"+getAge.invoke(student));
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容