您的位置:首页 > 编程语言 > Java开发

java.lang.reflect操作对象属性(域)的值

2015-10-28 22:09 417 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: