Accessing Java static final variable value through reflection

前端 未结 4 1936
轮回少年
轮回少年 2020-11-27 18:13

Can the value of a Java static final class variable be retrieved through reflection?

4条回答
  •  情话喂你
    2020-11-27 19:13

    If open-source libraries are allowed on your project you can use

    FieldUtils.readDeclaredStaticField

    public class Test {
        public final static String CONSTANT="myConstantValue";
    }
    

    In another class you can use:

    Object value = FieldUtils.readDeclaredStaticField(Test.class, "CONSTANT");
    System.out.println(value);
    

    You will see "myConstantValue" in the console.

提交回复
热议问题