通过java上的配置文件实例化对象

时间:2016-01-05 15:18:03

标签: java oop object properties

我有这个对象:

public class TheObjectToInstantiate{
 public String Name;
 public String Surname;
 public TheObjectToInstantiate(){
 }
}

我想用配置文件实例化一个 TheObjectToInstantiate [] 数组:

TheObjectToInstantiate1.Name="Pippo"
TheObjectToInstantiate1.Surname="PippoSurname"
TheObjectToInstantiate2.Name="Pluto"
TheObjectToInstantiate2.Surname="PlutoSurname"

我试过

public ConfigReader(){
    Properties prop = new Properties();
    InputStream input = null;

    try {

        input = new FileInputStream("configuration.prop");
        prop.load(input);

        Enumeration<?> e = prop.propertyNames();
        while (e.hasMoreElements()) {
            String key = (String) e.nextElement();
            String value = prop.getProperty(key);
            ......
        }

    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

手动扫描所有属性并实例化对象。

有些方法或开源包装器可以在不手动比较所有属性的情况下执行此操作吗? 感谢

1 个答案:

答案 0 :(得分:1)

使用json文件更容易,并使用像Jackson这样的库反序列化它们。您也可以查看http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jacksonHow to use Jackson to deserialise an array of objects

[1, 4, 7, 8, 12]

json文件将是这样的:

public class TheObjectToInstantiate {
    public String Name;
    public String Surname;
    public TheObjectToInstantiate(){}
}

public class JacksonExample {
    public static void main(String[] args) {

    ObjectMapper mapper = new ObjectMapper();

    try {
        // Convert JSON string from file to Object
        TheObjectToInstantiate object = mapper.readValue(new File("G:\\myobject.json"), TheObjectToInstantiate.class);
    } catch (IOException e) {
            e.printStackTrace();
    }

}

您也可以反序列化对象列表:

{
  "Name" : "foo",
  "Surname" : "bar"
}

它还支持更复杂的结构,如嵌套对象或主对象中的List或其他对象数组。