public class ReflectTest {
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
//1.创建一个Employee对象
Employee richard = new Employee("Richard", 3500);
//2.得到Employee对象的Class对象
Class employeeClass = Employee.class;
//3.利用Class对象的getDeclaredField()方法, 传入对象实例域的名字, 如"salary", 得到对应域对象的Field对象
Field salaryField = employeeClass.getDeclaredField("salary");
//4.利用Field对象, 操作(访问/修改)任意Employee对象的salary域
salaryField.setAccessible(true);
salaryField.set(richard, 6500);
Object obj = salaryField.get(richard);
System.out.println((Integer) obj);
System.out.println("-------------------");
/**
* 测试 使用反射调用方法
*/
//1.使用方法名得到对应的方法的Method对象, 注意, 为了准确的找到想要的方法, 需要提供方法的参数类型
Method setNameMethod = employeeClass.getDeclaredMethod("setName", String.class);
//2设置访问权限
setNameMethod.setAccessible(true);
//3.调用方法, 调用时传入参数
setNameMethod.invoke(richard, "sam");
//4.验证通过反射调用的方法, 得到了执行
System.out.println(richard.getName());
}
}
网友评论