While it's technically possible to do this using reflection, I'd strongly recommend you to rethink your structure, and consider one of the alternatives that have been mentioned in the other answers.
The simplest would probably be to use a map
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
public class VariableNameTest
{
private static final Map<String,Integer> map;
static
{
Map<String, Integer> m = new LinkedHashMap<String, Integer>();
m.put("DRAGON",5);
m.put("SNAKE",6);
map = Collections.unmodifiableMap(m);
}
public static void main(String[] args)
{
System.out.println(getValue("DRAGON"));
System.out.println(getValue("SNAKE"));
System.out.println(getValue("Boo!"));
}
public static int getValue(String name)
{
Integer i = map.get(name);
if (i == null)
{
// Do some error handling here!
}
return i;
}
}
But if your intention is to extend this with additional functionality, you should probably introduce a class like it was recommended in https://stackoverflow.com/a/23846279/3182664
Just for completeness: The reflection solution, not recommended!
import java.lang.reflect.Field;
public class VariableNameTest
{
static final int DRAGON = 5;
static final int SNAKE = 6;
public static void main(String[] args)
{
System.out.println(getValue("DRAGON"));
System.out.println(getValue("SNAKE"));
System.out.println(getValue("Boo!"));
}
private static int getValue(String name)
{
try
{
Class<?> c = VariableNameTest.class;
Field f = c.getDeclaredField(name);
return f.getInt(null);
}
catch (NoSuchFieldException e)
{
// Many things
e.printStackTrace();
}
catch (SecurityException e)
{
// may cause
e.printStackTrace();
}
catch (IllegalArgumentException e)
{
// this to
e.printStackTrace();
}
catch (IllegalAccessException e)
{
// fail horribly
e.printStackTrace();
}
return 0;
}
}