如何使用reflection定义动态setter和getter?

我在资源包的循环中列出了一个字符串,字段名称列表。 我创建一个对象然后使用循环我想为该对象设置值。 例如,对于对象

Foo f = new Foo(); 

使用参数param1,我有字符串“param1”,我想以某种方式将“set”与“set”+“param1”连接起来,然后将其应用于f实例:

 f.setparam1("value"); 

对于吸气剂也一样。 我知道反思会有所帮助,但我无法做到。 请帮忙。 谢谢!

你可以做这样的事情。 您可以使此代码更通用,以便您可以使用它来循环字段:

 Class aClass = f.getClass(); Class[] paramTypes = new Class[1]; paramTypes[0] = String.class; // get the actual param type String methodName = "set" + fieldName; // fieldName String Method m = null; try { m = aClass.getMethod("confirmMsg", paramTypes); } catch (NoSuchMethodException nsme) { nsme.printStackTrace(); } try { String result = (String) m.invoke(f, fieldValue); // field value System.out.println(result); } catch (IllegalAccessException iae) { iae.printStackTrace(); } catch (InvocationTargetException ite) { ite.printStackTrace(); } 

Apache Commons BeanUtils做到了。