Java convention for storing all defined Strings -


what's java's main convention storing predefined set of strings? right have class contains of strings use, feels there's definietly better way this.

this i'm doing within my_strings.java class

public final static string s1 = "test"; public final static string s2 = "test2"; ... 

you can use resource bundles. create file called messages.properties in src or subdirectory corresponding desired package , add strings in following manner. no quoting needed.

classthatusesastring.stringname=foo anotherclass.stringname=bar anotherclass.anotherstring=baz 

you can access these strings follows:

resourcebundle rsrc = resourcebundle.getbundle("messages"); 

and then:

rsrc.getstring(stringname); 

for example, if fooclass requires string quxstring, add messages.properties:

fooclass.quxstring=waldo here 

notice lack of quotes. grab with:

rsrc.getstring("fooclass.quxstring"); 

this not enforce class boundaries , naming class convenience.

if strings related closely, enum may better, either directly, or specifying message names different localizations(i.e. enum contains "econnrefused" , "econnaborted" , map "connection refused" , "connection aborted" in 1 bundle , "conexión rechazada"/"conexión abortada" in bundle

eclipse users: eclipse automagically (though in more complex fashion) source→externalize strings


Comments