简体   繁体   中英

Instantiate objects by configuration file on java

I have this object:

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

I want to instantiate an array of TheObjectToInstantiate[] with configuration file:

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

I've tried with

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

}

scanning all properties and instatiate object manually.

There are ways or open source wrapper to do this without manually compare all properties? Thanks

It's easier to use json files and deserialize them with libraries like Jackson. You may also check http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson and How to use Jackson to deserialise an array of objects

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

}

json file would be like this:

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

you can also deserialize a list of objects:

List<TheObjectToInstantiate> myObjects = mapper.readValue(new File("G:\\myobjectlist.json"), new TypeReference<List<TheObjectToInstantiate>>(){});


[{
    "Name" : "foo1",
    "Surname" : "bar1"
},
{
    "Name" : "foo2",
    "Surname" : "bar2"
}]

It also supports more complex structures like nested objects or a List or array of other objects inside your primary object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM