| Real'sHowTo |
|
|
Custom Search
|
| Real'sHowTo |
|
|
Custom Search
|
import java.lang.reflect.*;
public class ReflectUtils {
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
*/
}
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);
}
}
class TestClass {
public double firstValue = 3.1416;
public int secondValue = 42;
public String thirdValue = "Hello world";
}
Written and compiled by Réal Gagnon ©1998-2013
[ home ]