• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Dynamic Constants Access

 
Lance Douglas
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1923
Linux Postgres Database Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)
{
//...............
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic