aspose file tools*
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
Author

Dynamic Constants Access

Lance Douglas
Greenhorn

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.


http://home.arcor.de/hirnstrom/bewerbung
avaya sahu
Greenhorn

Joined: Oct 16, 2001
Posts: 14
Hi,

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;
try
{
Field f = (Language.class).getField(Global.LANG.toUpperCase());
try
{
lang =f.getInt(Language.class);
}
catch(IllegalAccessException ise)
{
//...........
}
}catch( NoSuchFieldException ne)
{
//...............
}
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Dynamic Constants Access
 
Similar Threads
Application globals / constants : Interface vs.public final
Class initialization error!
Interfaces
Regarding type safe enum design pattern
Enum vs Constant File