码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-10-28 23:04:19      阅读:398      评论:0      收藏:0      [点我收藏+]

标签:

 

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

 

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

标签:

原文地址:http://www.cnblogs.com/softidea/p/4918870.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!