• Post Reply Bookmark Topic Watch Topic
  • New Topic

Accessing constants by variable name  RSS feed

 
Barry Brashear
Ranch Hand
Posts: 303
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a constants file that contains error codes such as the following

String ERROR_100 = "Some error message";

I will get the error code back from some service which would be the 100.
How can I access the error code string of ERROR_100 with the number 100?
Can you build a string this way?

Thanks.
 
Barry Higgins
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The easiest way I could think of would be to put all your error messages into an array and get them back by index. This would be a terrible way of doing it because if you change the order of eg. by adding one to the start of the array you'd have to go and make updates all through your code.

Is there a reason you don't just implement a properties file?
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A Map would do nicely:

myMap.put("100", "Some Error Message");

message = MessageRepository.get("100");

You might want to read from a file and add to a map. A properties file as mentioned before would do, or a simple text file. It's neat to have messages in a file so you can spellcheck or edit for consistent style and tone in one place.
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An array would do it.
A Map would do it nicely
An enum would do it nicest.
 
Chengwei Lee
Ranch Hand
Posts: 884
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, they all works. But what happens if I (or rather, my clients) need to change my messages? They won't have access to my source codes or they don't have the slightest idea on how to compile a Java class.

The best is to use a properties file to keep the key & message. The properties file is a human-readable & understandable text file that can be easily altered. The best part is you don't need to touch your working codes.

Once you've the properties file, the array, map or enum methods can come in place.

HTH
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!