how to get a constant in java with class

后端 未结 6 1286
一个人的身影
一个人的身影 2021-02-13 14:51

basically I need to get a constant for a class however I have no instance of the object but only its class. In PHP I would do constant(XYZ); Is there a similar way

6条回答
  •  粉色の甜心
    2021-02-13 15:23

    If you don't want to actually load or initialize the class, ClassGraph can do this:

    String fieldVal;
    try (ScanResult scanResult =
            new ClassGraph().whitelistClasses(className).enableFieldInfo().scan()) {
        fieldVal = (String) scanResult.getClassInfo(className).getFieldInfo("s")
                .getConstantInitializerValue();
    }
    

    N.B. this works only for constant initializer values (values that can be computed without object instantiation, with the exception of String), assigned to static final fields. The compiler can produce a constant at compiletime for simple arithmetic and simple string concatenation.

    (disclaimer, I am the author of ClassGraph)

    Simply using reflection to access static fields is simpler, if you don't mind loading the class, as given in this other answer: https://stackoverflow.com/a/4076792/3950982

提交回复
热议问题