Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type-safe configuration read/write library for Java?

Is there a good configuration library for Java which will allow me to read settings in a type-safe way? For example by taking my crafted IConfiguration interface with getters and setters declared and allowing me to read/write configuration via it.

It's a bit boring to read settings using properties.getProperty("group.setting") and then cast it to needed type. Apache commons configuration allows to use something like config.getDouble("number"), but "number" here is a string again and I would like to be able to do something like double value = config.GetNumber().

like image 581
Vladislav Rastrusny Avatar asked May 14 '11 23:05

Vladislav Rastrusny


2 Answers

OWNER library does what you want.

like image 50
Alexey Romanov Avatar answered Nov 15 '22 20:11

Alexey Romanov


My Config4J library (which is mature and well-documented but not widely known) provides most of what you want.

In particular, Config4J provides type-safe "lookup" (that is, "get") operations for built-in types such as string, boolean, int, float, and durations (such as "500 milliseconds" or "2.5 days"). A duration string is automatically converted to an integer value denoting (your choice of) milliseconds or seconds.

The library also provides building blocks so you can perform type-safe lookups on strings of the form "<float> <units>" (for example, "2 cm" and "10.5 meters" for distances) or "<units> <float>" (for example, "$0.99" or "£10.00" for money).

The library also provides a trivial-to-use schema validator (in case that is of interest to you).

The way Config4J fails to meet your stated requirements is that the "insert" (that is, "put") functionality of the library works only in terms of strings. So you would have to convert an int/boolean/float/int-denoting-duration/whatever value into a string and then "insert" that into the Config4J object. However, that -to-string conversion is not usually a burdensome task.

After inserting some name=value pairs into the Config4J object, you can then call dump() to serialise the entire object into a string that you can then write back to a configuration file.

Reading Chapters 2 and 3 of the "Getting Started Guide" (PDF, HTML) should give you an a good-enough overview of Config4J to decide if it fits your needs. You might also want to look at the "simple-encapsulation" demo, which is supplied in the source-code download (compressed tar, zip).

like image 42
Ciaran McHale Avatar answered Nov 15 '22 21:11

Ciaran McHale