Home > Back-end >  How Can I create a dynamic reference to a Constant?
How Can I create a dynamic reference to a Constant?

Time:07-27

I want to make a dynamic call to get a Constant from Constants.java based on the field Name?

Ex.

public class Constants {
  
  public static final String FIELD1 = "field1";
  public static final String FIELD2 = "field2";
}

And how can I get value based on the field paramter?

private String getConstant(String field){
  //field parameter can be many values for field paramter not just Field1 or Field2
  return Constant.field;
}

CodePudding user response:

You need to read about reflection mechanism. Try this:

private String getConstant(String field) throws NoSuchFieldException, IllegalAccessException {
  // one field only:
  return Constants.class.getField(field).get(null);
}

CodePudding user response:

Look like you need an enum (which are similar to constants):

public enum Constant {
    FIELD1("field1"),
    FIEL21("field2"),
    // etc
    ;
    private String str;

    Constant(String str) {
        this.str = str;
    }
    
    public String getStr() {
        return str;
    }
}

Then to get the String:

private String getConstant(String field) {
    return Constant.valueOf(field).getStr();
}
  • Related