Get a variable value from the variable nameTag(s): Language
About cookies on this site
We use cookies to collect and analyze information on site performance and usage,
to provide social media features and to enhance and customize content and advertisements.
import java.lang.reflect.Field;
public class ReflectUtils {
private ReflectUtils (){ }
@SuppressWarnings("rawtypes")
public static Object getValueOf(Object clazz, String lookingForValue)
throws Exception {
Field field = clazz.getClass().getField(lookingForValue);
Class clazzType = field.getType();
if (clazzType.toString().equals("double"))
return field.getDouble(clazz);
else if (clazzType.toString().equals("int"))
return field.getInt(clazz);
// else other type ...
// and finally
return field.get(clazz);
}
public static void main(String[] args) throws Exception{
TestClass test = new TestClass();
System.out.println (ReflectUtils.getValueOf(test,"firstValue"));
System.out.println (ReflectUtils.getValueOf(test,"secondValue"));
System.out.println (ReflectUtils.getValueOf(test,"thirdValue"));
/*
output :
3.1416
42
Hello world
*/
}
}
class TestClass {
public double firstValue = 3.1416;
public int secondValue = 42;
public String thirdValue = "Hello world";
}