Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get a constant in java with class

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 of retrieving a constant in JAVA?

I need it to facilitate a dynamic getMethod call

Class parameterType = Class.forName(class_name);
object.setProperty(field name, field value, parameterType);

the set property method would then get the correct method and set the specified property, however I cant get a method which has int as parameter type without using Interger.TYPE

like image 415
luxerama Avatar asked May 19 '10 10:05

luxerama


People also ask

How do you find a constant in Java?

To turn an ordinary variable into a constant, you have to use the keyword "final." As a rule, we write constants in capital letters to differentiate them from ordinary variables. If you try to change the constant in the program, javac (the Java Compiler) sends an error message.

Can we declare constant in Java?

How to declare constant in Java? In Java, to declare any variable as constant, we use static and final modifiers. It is also known as non-access modifiers. According to the Java naming convention the identifier name must be in capital letters.


2 Answers

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

like image 183
user85155 Avatar answered Oct 06 '22 02:10

user85155


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!
like image 43
gustafc Avatar answered Oct 06 '22 01:10

gustafc