- package com.itheima;
- import java.lang.reflect.Field;
- class Person1{
- private String name;
- private int age;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public Person1(String name, int age) {
- super();
- this.name = name;
- this.age = age;
- }
- //重写toString方法
- @Override
- public String toString() {
- return "Person1 [name=" + name + ", age=" + age + "]";
- }
-
- }
- public class Test1 {
- public static void main(String args[]){
- //创建一个对象
- Person1 p=new Person1("zhangsan",23);
- System.out.println(p.toString());
- //调用setProperty方法
- setProperty(p,"age",18);
- System.out.println(p.toString());
- }
-
- /*此方法可将obj对象中名为propertyName的属性的值设置为value.
- * */
- public static void setProperty(Object obj, String propertyName, Object value){
- //Field[] declaredFields = obj.getClass().getDeclaredFields(propertyName);
- try {
- //通过反射获得相应字段
- Field field=obj.getClass().getDeclaredField(propertyName);
- //设置暴力反射
- field.setAccessible(true);
- //设置字段值
- field.set(obj, value);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
复制代码 |