Win a copy of Terraform in Action this week in the Cloud forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

Dynamic Constants Access

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 1923
Scala Postgres Database Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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)
{
//...............
}
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic