Have a lot final strings, what do you recommend to place them in java?
Want to开发者_开发问答 create a seperate class and store all the strings inside it. Is this a way good or there is better way?
It really comes back to what those strings are for. For example if they contain what are effective static constants they might be best placed inside the classes that require them. Or if used by a number of classes perhaps enums might be a better solution because it allows you to group and effectively type them.
Then you have to consider if they are strings that the users will see. In that case you may need to store them in properties file or even a database. Especially if you want to allow for internationalisation at some point in the future.
Some alternatives: Put them on disk and read them on demand, put them as constants into an interface, use enums instead. What are you doing with the strings?
I'd suggest to use ResourceBundle or Properties.
public class TestResource extends ListResourceBundle{
public Object[][] getContents() {
Object [][]mydata={ {"key1","Data1"}, {"key2","Data2"}};
return mydata;
}
}
public class Resx{
public static void main(String []args) {
try{
ResourceBundle rb=ResourceBundle.getBundle("TestResource");
Enumeration e=rb.getKeys();
String key;
while(e.hasMoreElements()){
key=(String) e.nextElement();
System.out.println(key + " " + rb.getObject(key));
}
}catch(Exception ex) {
ex.printStackTrace();
}
}
}
I never had a program where it would have made sense to store all Strings in a separate file.
- Strings are part of self-documenting code.
- Putting all strings in a central file breaks modularisation
精彩评论