Monday, May 11, 2015

JAVA: get a constant value by its name

Hello JAVA coders, 

This is a quick note on a JAVA trick. Lets say we have a list of constants defined in a Class. Lets assume the code is already implemented and yes, there maybe better data structures to handle this situation with nice patterns etc... However, here we need a quick fix. We just need to get the value of one of this constants and we do not know the name of the constant at compile time. Assume for example that the name of the constant is a an argument. 

Well, its is not that difficult, with just two lines of code we can get the value of any constant by its name. Just by using a bit of reflection code. Here is the example code:
import java.lang.reflect.Field;
.....
Field constantField = <ClassWithConstants>.class.getField(<constantName>);
String constantValue = (Type) constantField.get([classInstantce]);

Where "classInstance" is optional and it would be an instance of the Class we we have one available. And "Type" is the type of the constant value, i.e String, Integer, etc...

This is it, simple and easy. Then when you have time, remember to come back and re-factor the code to make a nice data-structure.

Thanks for reading,
Keep on hacking,

Posted by Marc Andreu.

No comments: