Results 1 to 1 of 1
-
Getting variable value from a variable name
Presented below is an interesting example that gets a variable value from the variable name
Java Code: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"; }
Similar Threads
-
Increment a Variable
By rhm54 in forum New To JavaReplies: 2Last Post: 06-14-2008, 02:57 AM -
getting the value of variable
By Lehane_9 in forum New To JavaReplies: 2Last Post: 03-05-2008, 01:42 AM -
Variable No. of Arguments
By Gajesh Tripathi in forum New To JavaReplies: 2Last Post: 10-31-2007, 02:50 PM -
Create a new variable
By mathias in forum New To JavaReplies: 1Last Post: 08-07-2007, 06:48 AM -
String Variable
By Eric in forum Advanced JavaReplies: 1Last Post: 06-06-2007, 04:30 AM
Bookmarks