简体   繁体   中英

How to access constants from a java class through other variable?

I have java class which has all constants as given below:

public final class CategoryIDs {

  public static final String Extraction_of_natural_gas = "1111";
  public static final String Mining_of_hard_coal = "2222";
  public static final String Mining_of_iron_ores = "3333";
  public static final String Mining_of_lignite = "4444";

}

Now I want to access these constants in some other class through a variable which holds name of the variable.

For example:

String temp = "Extraction_of_natural_gas";

Using this temp variable I want to access constants from above class. But I can't do CategoryIDs.temp as it isn't allowed. So what is the best way to achieve this?

You can use reflection to extract it:

String value = (String) CategoryIDs.class.getField(temp).get(null);

The null argument passed to get signifies this is a static field, and no instance is required in order to get its value.

Note that this technique is very error prone. The code above doesn't contain any error checking or exception handling in order to make it easier to read, but a real application should probably contain them.

If you really, really need to do this with your current structure, you could use reflection.

However, you may well find that an enum would be a better fit. Something like:

public enum CategoryID {

    EXTRACTION_OF_NATURAL_GAS("Extraction_of_natural_gas", 1111),
    MINING_OF_HARD_COAL("Mining_of_hard_coal", 2222),
    MINING_OF_IRON_ORES("Mining_of_iron_ores", 3333),
    MINING_OF_LIGNITE("Mining_of_lignite", 4444);

    private static final Map<String, CategoryID> keyMap;

    static {
        keyMap = new HashMap<>();
        for (CategoryID category : CategoryID.values()) {
            keyMap.put(category.getKey(), category);
        }
    }

    private final String key;
    private final int value;

    public int getValue() {
        return value;
    }

    public String getKey() {
        return key;
    }

    private CategoryID(String key, int value) {
        this.key = key;
        this.value = value;
    }

    public static CategoryID fromKey(String key) {
        return keyMap.get(key);
    }
}

Benefits of this approach:

  • You separate the name in the code (which is now more conventional for Java) from the key you'd provide in the data. That means you can use whatever keys you'd like in the data, including ones with spaces in etc. They no longer need to be valid identifiers.
  • You still get compile-time safety when you refer to the enum values from code.
  • You get better safety as you'll never accidentally use a string instead of a category ID, which you could easily have done using your constants.

I think you are looking for introspection. This is the "read only" part of reflection, in which you can retrieve the value of an object.

The code would be as follows, pieced for ease of understanding:

    Object value = null;
    String constName = "Bar";
    Field constant = Foo.class.getField( constName );

    if ( constant != null ) {
        value = constant.get( null );
    }

    if ( value != null ) {
        System.out.println( value );
    } else {
        System.out.println( "Constant " + constName + " was not found." );
    }

Interestingly, you can access the value from the Field object calling get() , and you pass null because the constant is static, and thus you don't have an instance to extract the value from.

You can find the whole code here: http://ideone.com/v4fcvH

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM