I wanted an opinion about an idea I had regarding the use of config.properties, static classes and the use of reflection.
I have to load some preferences at application startup, for that I will be using config.properties. Certain properties within config.properties will be changed during various points in the program. So, instead of opening, searching for the property, updating and closing properties.config - I was thinking I could use a static class to read and write values, use reflection to write values back and forth between static class and properties.config file during application startup and close.
Is there a better approach I should be considering? Should I be avoiding static class?
Here is simplified code
//Class with static variables, the values get used and updated at
//various points within the program. For example prop1 gets updated and used
//at a different points in the program. Also, they are active at
//different points in the program than prop1 and prop2.
//values need to be saved for application startup.
public class StaticProp {
public static String prop1 = "a";
public static String prop2 = "b";
public static String prop3 = "c";
}
During application close, using Reflection - write values to properties.config
private void writeConfigProp() {
Properties prop = new Properties();
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream("resources/config.properties");
Field[] fields = StaticProp.class.getDeclaredFields();
for (Field field : fields) {
try {
prop.setProperty(field.getName(), Utility.tryParseVal(field.get(null)));
} 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();
}
}
}
}
During application startup, using Reflection - read properties.config to static class.
/**
* Read Config Properties
*/
private void readConfigProp() {
Properties prop = new Properties();
InputStream inputStream = null;
try {
inputStream = new FileInputStream("resources/config.properties");
prop.load(inputStream);
Field[] fields = PropConfig.class.getDeclaredFields();
for (Field field : fields) {
try {
try {
field.set(null, 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();
}
}
}
}