user1714575 user1714575 - 12 days ago 7
Java Question

Read in file for constants #java

I want to read in a datafile that has several constants for my program (e.g. MAXARRAYSIZE).

I then want these constants to be accessible anywhere in my program by typing something like: ConstantsClassName.MAXARRAYSIZE. How do I implement this class?

Once assigned from the datafile, these constants will never again change value during program execution.

Thanks.

Answer

Use a static bloc in ConstantsClassName class.

public class ConstantsClassName{
    public static final  String MAXARRAYSIZE;
    static{
        // read your file and store the data in;
        MAXARRAYSIZE = valueRetrievedFromFile;
    }
}

MAXARRAYSIZE should be MAX_ARRAY_SIZE if you follow Java conventions for constants declaration.

Comments