This week's book giveaway is in the Agile forum.
We're giving away four copies of The Software Craftsman and have Sandro Mancuso on-line!
See this thread for details.
The moose likes Java in General and the fly likes Dynamic Constants Access Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of The Software Craftsman this week in the Agile forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Dynamic Constants Access" Watch "Dynamic Constants Access" New topic

Dynamic Constants Access

Lance Douglas

Joined: May 20, 2005
Posts: 1
Hello all,

Thanks in advance for any help!

I am trying to have dynamic access to a constant as follows:

//Code from other samePackage.class.method
// Global.LANG = "English" OR "French" for this example
int lang = Language.(Global.LANG.toUpperCase());
....................^ error (identifier) expected!

//Class with constants I want access to
public final class Language
public static final int ENGLISH = 6;
public static final int FRENCH = 7;

Is there a way to dynamicaly declare the identifier in JAVA?
Basically like an e_v_a_l() function or a {eval} statement in JAVA?

No additional classes can be added to the system allow for this functionality.
Stefan Wagner
Ranch Hand

Joined: Jun 02, 2003
Posts: 1923

If you can not change the Language-class, there is no such short way.

A Map might help you:

Using 1.5 code, enum would be of more value, I guess.
avaya sahu

Joined: Oct 16, 2001
Posts: 14

it is possible. I think you are trying to fetch field name from Global class. if the Global.LANG ="english" you want to fetch the corresponding constant value from Language class.

You have to use reflection for this. There is no language feature which directly support expression evaluation as you mentione in the post.

but following code will work fine

int lang = 0;
Field f = (Language.class).getField(Global.LANG.toUpperCase());
lang =f.getInt(Language.class);
catch(IllegalAccessException ise)
}catch( NoSuchFieldException ne)
Have you tried LearnNowOnline?
subject: Dynamic Constants Access