写一个方法实现吧obj对象里的propertyName的属性值设置为value

xiaoxiao2021-02-28  103

由于方法不确定,属性名也不确定,因此属性的类型也不确定,如果是私有的就无法访问,因此为了解决这个问题我们可以想到万能的反射。 写一个setProperty方法达到我们的效果,可以被很多类进行调用:

public class Demo{ public void setProperty(Object obj,String propertyName,Object value) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException{ //获得对象obj的字节码文件对象 Class c = obj.getClass(); //获得propertyName字段 Field field = c.getDeclaredField(propertyName); field.setAccessible(true); field.set(obj,value); //设置obj对象的field字段的值为value } }

接下来我们来调用一下这个方法,测试结果是否为对的。 新建一个Test类,编写测试代码;还有一个Student类作为需要改变的对象。

class Student{ String name; private int age; @Override public String toString() { return name + "---" + age; } } public class Test { public static void main(String[] args) throws SecurityException, IllegalArgumentException, NoSuchFieldException, IllegalAccessException { Student s = new Student(); Demo demo = new Demo(); demo.setProperty(s, "name", "梨梨"); demo.setProperty(s, "age", 21); System.out.println(s); } } 输出为:梨梨---21
转载请注明原文地址: https://www.6miu.com/read-39701.html

最新回复(0)