Java - Check properties file at compile time

1.5k Views Asked by At

I need some advices from you today.

I am working on a project which uses a huge constants holding class.

There are lots of

public static final String CONST_NAME = "const_value";

I am getting those using MyConstClass.CONST_NAME but now I need to externalise them in order to configure the project.

So I thought of 2 ways of doing this :

  1. Configuring the project through multiple MyConstants.java

I would compile one of them with the rest of my java classes.

Since those are constants it will ensure compile time safety.

  1. Adding a .properties file

This file would set every constants I need in the code.

I would get them with something like MyConstants.get("CONST_NAME");

Far more elegant than having multiple java classes (right?) that you would / would'nt compile with the rest of the project.

But it doesn't ensure a compile time safety which is quite required to avoid some man made mistakes.

So here is my questions :

  1. Is it possible to check AT COMPILE TIME that all the properties I get with MyConstants.get("CONST_NAME"); are existing in my .properties file?
  2. Is there a better way?

PS:

I found topics like this one and this other one but I don't think that's the way to do it.

2

There are 2 best solutions below

0
On BEST ANSWER

It's certainly possible to do all sorts of things at compile time with custom compiler tasks etc, but I don't think it's very practical.

Personally, I'd have an enum of property keys and property files for their value configurations - something like:

public enum {
    CONST_NAME
}

and

MyConstants.get(CONST_NAME)

and calling.toString() on the enum to get the textual key representation.

0
On

I agree that there is always a way. But I think the simplest way would be to write a unit test that checks that all the configuration values are set. This way you can fail the build if the configuration is not complete.