使用java反射,您可以确定可用的方法/字段。
您可以使用此示例将您的键/值对传递给doReflection
方法,以在Bean类的实例中设置属性的新值。
public class Bean {
private String id = "abc";
public void setId(String s) {
id = s;
}
/**
* Find a method with the given field-name (prepend it with "set") and
* invoke it with the given new value.
*
* @param b The object to set the new value onto
* @param field The name of the field (excluding "set")
* @param newValue The new value
*/
public static void doReflection(Bean b, String field, String newValue) throws NoSuchMethodException,
SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Class<? extends Bean> c = b.getClass();
Method id = c.getMethod("set" + field, String.class);
id.invoke(b, newValue);
}
public static void main(String... args) throws NoSuchMethodException, SecurityException, IllegalArgumentException,
InvocationTargetException, IllegalAccessException {
Bean bean = new Bean();
System.out.println("ID before: " + bean.id);
doReflection(bean, "Id", "newValue");
System.out.println("ID after: " + bean.id);
// If you have a map of key/value pairs:
Map<String, String> values = new HashMap<String, String>();
for(Entry<String, String> entry : values.entrySet())
doReflection(bean, entry.getKey(), entry.getValue());
}
“* Java不给我选择以字符串格式调用方法*” - 我不明白 – Maroun 2013-03-17 15:22:26