I have a bunch of constants in my code for various custom properties of my system. I move all of them to a central .properties file. My current solution is to have one Properties.java that statically loads the .properties file and provides various getter methods as follows:
public class Properties { private static final String FILE_NAME = "myfile.properties"; private static final java.util.Properties props; static { InputStream in = Properties.class.getClassLoader().getResourceAsStream( FILE_NAME); props = new java.util.Properties(); try { props.load(in); } catch (IOException e) { throw new RuntimeException(e); } } public static String getString(Class<?> cls, String key) { return props.getProperty(cls.getName() + '.' + key); } public static int getInteger(Class<?> cls, String key) { return Integer.parseInt(getString(cls, key)); } public static double getDouble(Class<?> cls, String key) { return Double.parseDouble(getString(cls, key)); } }
The only problem is that for every constant I get from this file, I have a template:
private final static int MY_CONSTANT = Properties.getInteger( ThisClass.class, "MY_CONSTANT");
I donβt think I want to use Spring or the like, as it looks like even more collapses. I was hoping to use custom annotation to solve the problem. I found this tutorial , but I can't figure out how to get the functionality that I want from annotation processing. Java docs were even less useful. This should be what I would have to do at compile time. I know the class names and fields.
What I think looks something like this:
@MyAnnotation private static final int MY_CONSTANT;
Does anyone know how I will do this, or at least the best practices for what I want to do?
source share