how to get a constant in java with class
If this constant is metadata about the class, I'd do this with annotations:
First step, declare the annotation:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Abc {
String value();
}
Step two, annotate your class:
@Abc("Hello, annotations!")
class Zomg {
}
Step three, retrieve the value:
String className = "com.example.Zomg";
Class<?> klass = Class.forName(className);
Abc annotation = klass.getAnnotation(Abc.class);
String abcValue = annotation.value();
System.out.printf("Abc annotation value for class %s: %s%n", className, abcValue);
Output is:
Abc annotation value: Hello, annotations!
You might look for sth. like
Foo.class.getDeclaredField("THIS_IS_MY_CONST").get(null);
or
Class.forName("Foo").getDeclaredField("THIS_IS_MY_CONST").get(null);
(thanks f-o-o)
Gets the value of a String constant (THIS_IS_MY_CONST) in class Foo.
Update
use null
as argument for get
thanks acdcjunior