使用 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());
}