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
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