反射类
/**
* @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));
}
}