Java/从字符串到Java代码
我有一些从文件中以字符串格式获取的值 例如,在文件A中,我有:Java/从字符串到Java代码,java,Java,我有一些从文件中以字符串格式获取的值 例如,在文件A中,我有: id = 342 name = Jonatan country = USA 此外,我还有一个类:person,其中包含以下字段: String id; String name; String country; String grades; String location; 我有所有领域的getter和setter 现在,我想创建一个新的person实例,它代表Jonatan。 但是-我不想更新所有字段,只更新我需要的字段 因此,
id = 342
name = Jonatan
country = USA
此外,我还有一个类:person
,其中包含以下字段:
String id;
String name;
String country;
String grades;
String location;
我有所有领域的getter和setter
现在,我想创建一个新的person实例,它代表Jonatan。
但是-我不想更新所有字段,只更新我需要的字段
因此,我要做的是下一步:从文件中获取详细信息,然后为每个do集合更新正确的值。例如,setName(Jonatan)
。问题是我的名称
是字符串格式。所以我不能使用setName——因为名称是字符串格式的,Java不允许我选择调用字符串格式的方法
有简单的方法吗?使用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());
}
公共类Bean{
私有字符串id=“abc”;
公共void setId(字符串s){
id=s;
}
/**
*查找具有给定字段名的方法(在其前面加上“set”)并
*用给定的新值调用它。
*
*@param b设置新值的对象
*@param field字段名称(不包括“set”)
*@param newValue新值
*/
公共静态void doReflection(Bean b、字符串字段、字符串newValue)抛出NoSuchMethodException,
SecurityException、IllegalAccessException、IllegalArgumentException、InvocationTargetException{
类您可以看看
该应用程序非常简单,可以调用个人调用的setId(“42”):
PropertyUtils.setSimpleProperty(person, "id", "42");
我喜欢@michael_的答案中有BeanUtils
。如果你不想这样做,你可以写:
Person person = new Person();
Properties properties = new Properties();
properties.load(new FileInputStream("the.properties"));
for (Object key : properties.keySet()) {
String field = (String) key;
String setter = "set" + field.substring(0, 1).toUpperCase() + field.substring(1);
Method method = Person.class.getMethod(setter, String.class);
method.invoke(person, properties.get(key));
}
不是使用流后关闭该流,这个简短的例子只适用于 String 这应该是一个注释。如果你把这个问题当作一个答案更新,那么至少举一个例子,这个例子是“java没有给我一个字符串格式调用方法的选择”——我不明白。