Java: Using key names from properties file without using hardcoded strings as keys -
problem statement
i have properties file that's accessed throughout java project.
example contents of .properties
file:
appname=myapp apptype=typea
let's access single property, appname
, throughout java project
props.getproperty("appname");
i don't want iterate through properties file property value; i'm getting single property value properties file. don't fact have access property using hardcoded string because can lead maintenance issues (i.e. changing instances of hardcoded string).
my current approach
in current approach, have utility class creates static final variables representing key names in properties file, , use variable access property value:
public static final string app_name = "appname"; ... props.getproperty(app_name);
but seems overkill because it's being redundant, , still potential maintenance concern. key exists in properties file, , i'm declaring them again in utility class.
is there more "maintenance-free" way of accessing key name in code when using methods access property values?
no, you're doing right. , it's maintenance-free.
using java enums preferable - i.e.
public class propertieswrapper { private final properties props; ... public string get(myenum key) { return props.get(key.tostring()); }
the reason if make string constant, can never change without recompiling code uses constant - because compiler replace constant "appname" @ compile-time.
if use enums , remove enum constant, code still need recompiling, won't appear fine when it's asking wrong thing. also, using tostring()
instead of name()
property name, free override tostring()
in enum return different constant name.
the down-side of using enums system can't not known @ compile-time without alternate way access properties
.
Comments
Post a Comment