jeudi 18 février 2016

Java reflection type cast array

I am storing information from the fields of an entity class Config in a properties file as key/value pairs.

fieldName1 = fieldValue1  
fieldName2 = fieldValue2  
...  

Until now I hardcoded it

Properties props = new Properties();
props.setProperty("pathToExe", config.getPathToExe()); 
// ...
Writer writer = new OutputStreamWriter(new FileOutputStream(configFile), StandardCharsets.ISO_8859_1);
props.store(writer, "");
writer.close(); 

But as I want to continuously extend the properties I was thinking about making it dynamic.
Config has fields of types String,String[] and int.
I read about reflection in Java but I am not familiar with it, see my code below:

Properties props = new Properties();
Field[] fields = config.getClass().getFields();
for (Field field : fields) {
    if (!field.getName().equals("oberservers")) {
        // is it a String[] field?
        if (field.getType().isArray()) {
            try {
                props.setProperty(field.getName(), String.join(";", /* how can I cast my String[] field here? */ );
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        else {
            try {
                props.setProperty(field.getName(), field.get(config).toString());
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
   }
}
// ...
Writer writer = new OutputStreamWriter(new FileOutputStream(configFile), StandardCharsets.ISO_8859_1);
props.store(writer, "");
writer.close();

How can I cast my String[] field?
Is this a clean approach at all or is there a cleaner way of doing this?

Thanks in advance.





Aucun commentaire:

Enregistrer un commentaire