How to dynamically extract a constant in java?

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

How can I dynamically retrieve a constant value depending on the passed class - that is, I want to do something like the following:

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

This is easy in PHP, but is it possible in Java? I saw that this problem was solved with accessors on a constant, but I want to get the constant directly. Annotations won't help me either.

thanks

+6
java constants
source share
2 answers

This can be achieved with reflection (also see the 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); } 

You may need to assign values ​​to the appropriate type.

+7
source share

Read chapter 19 to use interfaces only for determining types from Joshua Bloch Effective Java (in fact, please read the entire book)

Constants are not included in the interface !!! Constants should be tied to class implementations, not to interfaces.

Use fickle methods:

 // the implementing classes can define these values // and internally use constants if they wish to public interface BaseInterface{ String id(); // or getId() String root(); // or getRoot() } public interface MyInterface1 extends BaseInterface{ void myMethodA(); } public interface MyInterface2 extends BaseInterface{ void myMethodB(); } 

or use the listing to link things:

 public enum Helper{ ITEM1(MyInterface1.class, "foo", "bar"), ITEM2(MyInterface2.class, "foo2", "baz"), ; public static String getId(final Class<? extends BaseInterface> clazz){ return fromInterfaceClass(clazz).getId(); } public static String getRoot(final Class<? extends BaseInterface> clazz){ return fromInterfaceClass(clazz).getRoot(); } private static Helper fromInterfaceClass(final Class<? extends BaseInterface> clazz){ Helper result = null; for(final Helper candidate : values()){ if(candidate.clazz.isAssignableFrom(clazz)){ result = candidate; } } return result; } private final Class<? extends BaseInterface> clazz; private final String root; private final String id; private Helper(final Class<? extends BaseInterface> clazz, final String root, final String id){ this.clazz = clazz; this.root = root; this.id = id; }; public String getId(){ return this.id; } public String getRoot(){ return this.root; } } // use it like this String root = Helper.fromInterfaceClass(MyInterface1.class).getRoot(); 
0
source share

All Articles