2013-03-17 99 views
-1

我有一些价值,我从字符串格式从文件中获得。Java /从字符串到Java代码

例如,在文件的AI:

id = 342 
name = Jonatan 
country = USA 

另外,我有类:person下一个字段:

String id; 
String name; 
String country; 
String grades; 
String location; 

,我有getter和setter的所有字段。

现在,我想创建一个代表Jonatan的人的新实例。 但是 - 我不想更新所有的字段,只需要我需要的字段。

所以,我想要做的是下一步:从文件中获取详细信息,然后为每个人设置,并更新正确的值。例如,setName(Jonatan)。问题是我的name是字符串格式。所以我不能做setName - 因为名称是字符串格式,而Java不允许我以字符串格式调用方法。

有简单的方法吗?

+2

“* Java不给我选择以字符串格式调用方法*” - 我不明白 – Maroun 2013-03-17 15:22:26

回答

3

你可以看看Apache BeanUtils

该应用程序是非常简单 - 一个人通话的拨打SETID( “42”):

PropertyUtils.setSimpleProperty(person, "id", "42"); 
1

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

这应该是一条评论。如果你认为这是一个答案,至少应该举一个例子 – giorashc 2013-03-17 15:21:02

+0

用一个例子更新答案 – Joost 2013-03-17 15:43:27

1

我喜欢@ michael_s的答案与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性能。