package reflect;
import java.lang.reflect.Constructor;
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, InstantiationException {
String name = "Demo";
double salary = 20000.0;
String nameFieldName = "name";
String salaryFieldName = "salary";
Constructor<?>[] constructors = Person.class.getConstructors();
for (Constructor<?> constructor : constructors) {
Class<?>[] parameterTypes = constructor.getParameterTypes();
for (Class<?> parameterType : parameterTypes) {
System.out.println(parameterType.getName());
}
}
System.out.println("====================================");
//constructor
// 这个地方需要关注:如果是基本类型,就是double.class,不是Double.class
Constructor<Person> constructor = Person.class.getConstructor(String.class, double.class);
Person tom = constructor.newInstance("Tom", 3000000.0);
System.out.println(tom);
// get private Field
Person person = new Person(name, salary);
Field field = person.getClass().getDeclaredField(nameFieldName);
field.setAccessible(true);// 访问控制
System.out.println(field.get(person));
person = new Person(name, 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(String name, double salary) {
super();
this.name = name;
this.salary = salary;
}
public void doubleSalary() {
this.salary = this.salary * 2;
}
@Override
public String toString() {
return "Person [name=" + name + ", salary=" + salary + "]";
}
}
Output:
java.lang.String
double
====================================
Person [name=Tom, salary=3000000.0]
Demo
20000.0
Person [name=Demo, salary=20000.0]
200001.8