import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /*2015-10-28*/ public class RefactorDemo { /** * @param args * @throws NoSuchFieldException * @throws SecurityException * @throws IllegalAccessException * @throws IllegalArgumentException * @throws NoSuchMethodException * @throws InvocationTargetException */ public static void main(String[] args) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { String name = "Demo"; double salary = 20000.0; String nameFieldName = "name"; String salaryFieldName = "salary"; // get private Field Person person = new Person(name); Field field = person.getClass().getDeclaredField(nameFieldName); field.setAccessible(true);// 访问控制 System.out.println(field.get(person)); person = new Person(salary); field = person.getClass().getDeclaredField(salaryFieldName); field.setAccessible(true); System.out.println(field.getDouble(person)); // set private Field person = new Person(); field = person.getClass().getDeclaredField(nameFieldName); field.setAccessible(true); field.set(person, name); field = person.getClass().getDeclaredField(salaryFieldName); field.setAccessible(true); field.setDouble(person, salary); System.out.println(person); // process method person = new Person(); field = person.getClass().getDeclaredField(salaryFieldName); field.setAccessible(true); field.setDouble(person, 100000.9); Method method = person.getClass().getDeclaredMethod("doubleSalary"); method.invoke(person); System.out.println(field.getDouble(person)); } } class Person { private String name; private double salary; public Person() { super(); } public Person(double salary) { super(); this.salary = salary; } public Person(String name) { super(); this.name = name; } public void doubleSalary() { this.salary = this.salary * 2; } @Override public String toString() { return "Person [name=" + name + ", salary=" + salary + "]"; } }
http://www.cnblogs.com/xiaoxiaoyihan/p/4917095.html
时间: 2024-10-12 03:14:47