黑马程序员技术交流社区

标题: 请假这题怎么做 [打印本页]

作者: paozhuanyinyu    时间: 2014-9-19 21:23
标题: 请假这题怎么做
本帖最后由 paozhuanyinyu 于 2014-9-20 11:10 编辑

写一个方法,此方法可将obj对象中名为propertyName的属性的值设置为value.   
public void setProperty(Object obj, String propertyName, Object value){   
}


作者: Allencheng    时间: 2014-9-19 21:37
        public void setProperty(Object obj, String propertyName, Object value) throws Exception {                         Field f = obj.getClass().getDeclaredField(propertyName);                         f.setAccessible(true);                         f.set(obj, value);         }
作者: Allencheng    时间: 2014-9-19 21:38
Allencheng 发表于 2014-9-19 21:37
public void setProperty(Object obj, String propertyName, Object value) throws Exception {                         Field  ...

反射轻松解决
作者: THE_FUTURE    时间: 2014-9-19 21:42
射了。。。。
作者: paozhuanyinyu    时间: 2014-9-20 00:28
Allencheng 发表于 2014-9-19 21:37
public void setProperty(Object obj, String propertyName, Object value) throws Exception {                         Field  ...

这样是可以,但是好像用内省
作者: Huberry    时间: 2014-9-20 02:00
本帖最后由 Huberry 于 2014-9-20 02:03 编辑

复制代码
  1. public void setProperty(Object obj, String propertyName, Object value){   
  2.     PropertyDescriptor pd = new PropertyDescriptor(propertiesName, obj.getClass()); //获取这个属性
  3.     Method setPro = pd.getWriteMethod(); //取得这个属性的set方法
  4.     setPro.invoke(obj,value); //调用set方法
  5. }   
复制代码

            






欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2