lundi 27 avril 2015

Issues reading properties.config file using reflection

I have a static class and I write it's values into "properties.config" using reflection. This is done when I close my application. The static class values change during the program. I`m having trouble reading from the "properties.config" back to my static class during start up.

Any help is greatly appreciated.

field.set(null, prop.getProperty(field.getName()));

The object value is null, because it is a static class. But the program is erroring out here.

Write Method :

private void writeProperty() {
    Properties prop = new Properties();
    OutputStream outputStream = null;
    try {
        outputStream = new FileOutputStream("resources/config.properties");
        Field[] fields = PropertyCl.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                prop.setProperty(field.getName(), field.get(null).toString());
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        prop.store(outputStream, "Config for UI");
    } catch (IOException io) {
        io.printStackTrace();
    } finally {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Read Method : [Issues here]

/**
 * Reading from config.properties and setting fields in the static class
 */
private void readProperties() {
    Properties prop = new Properties();
    InputStream inputStream = null;

    try {
        inputStream = new FileInputStream("resources/config.properties");
        prop.load(inputStream);

        Field[] fields = PropertyCl.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                try {
                    field.set(null, prop.getProperty(field.getName()));
                    //System.out.println("Check >> " + field.get(field) + " ::: " + prop.getProperty(field.getName()));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}





Aucun commentaire:

Enregistrer un commentaire