File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
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)
I agree. Here's the link:
subject: Dynamic Constants Access
jQuery in Action, 3rd edition