aspose file tools
The moose likes Java in General and the fly likes Accessing constants by variable name Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Accessing constants by variable name" Watch "Accessing constants by variable name" New topic
Author

Accessing constants by variable name

Barry Brashear
Ranch Hand

Joined: Jun 05, 2001
Posts: 303
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

Joined: Jun 05, 2003
Posts: 89
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

Joined: Jan 29, 2003
Posts: 8791
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.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
An array would do it.
A Map would do it nicely
An enum would do it nicest.


Tony Morris
Java Q&A (FAQ, Trivia)
Chengwei Lee
Ranch Hand

Joined: Apr 02, 2004
Posts: 884
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


SCJP 1.4 * SCWCD 1.4 * SCBCD 1.3 * SCJA 1.0 * TOGAF 8
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Accessing constants by variable name
 
Similar Threads
A member interface is implicitly static
Enum vs Constant File
Use constants in jstl tag
Restriction on Constants
dumb array definition error, help!!!