Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically retrieve a constant in java?

Tags:

java

constants

I have several interfaces all with the same constants - ID and ROOT. I also have a method into which I pass an object that will be an implementation of one of these interfaces.

How can I dynamically retrieve the value of the constant depending on the class passed in - i.e. I want to do something like the following:

public void indexRootNode(Node node, Class rootNodeClass)
{
    indexService.index(node, rootNodeClass.getConstant('ID'), 
        rootNodeClass.getConstant('ROOT'));
}

In PHP this is easy, but is this possible in Java? I've seen this problem solved using accessors on the constant, but I want to retrieve the constant directly. Annotations won't help me here either.

Thanks

like image 758
Michael Jones Avatar asked Jul 06 '10 10:07

Michael Jones


1 Answers

This can be achieved using reflection (also see corresponding javadoc).

public void indexRootNode(Node node, Class rootNodeClass)
{
    Field idField = rootNodeClass.getField("ID");
    Object idValue = idField.get(null);
    Field roorField = rootNodeClass.getField("ROOT");
    Object rootValue = rootField.get(null);

    indexService.index(node, idValue, rootValue);
}

Maybe you may additionaly have to cast the values to the corresponding type.

like image 57
Janick Bernet Avatar answered Oct 12 '22 10:10

Janick Bernet