0

My question similar to others but it's little bit more tricky for me I have a Class DummyData having static defined variables

  1. public static String Survey_1="";
  2. public static String Survey_2="";
  3. public static String Survey_3="";

So, i call them DummyData.Survey_1 and it returns whole string value. Similarly do with DummyData.Survey_2 and DummyData.Survey_3 But the problem is when i call them Dynamically its not return their value. I have a variable data which value is change dynamically like (data=Survey_1 or data=Survey_2 or data=Survey_3) I use #Reflection to get its value but failed to get its value I use methods which I'm mentioning Below help me to sort out this problem.

Field field = DummyData.class.getDeclaredField(data); String JsonData = field.toString();

and DummyData.class.getDeclaredField("Survey_1").toString()

but this return package name, class name and string name but not return string value. What I'm doing can some help me??

AsifAli
  • 1
  • 4

2 Answers2

0

Getting the value of a declared field is not as simple as that.

You must first locate the field. Then, you have to get the field from an instance of a class.

Field f = Dummy.class.getDeclaredField(“field”);
Object o = f.get(instanceOfDummy);
String s = (String) o;
Bradley H
  • 339
  • 1
  • 7
0

Doing the simple toString() of the Field will actually invoke the toString() method of the Field object but won't access the value

You must do something like this:

Field field = SomeClass.class.getDeclaredField("someFieldName");
String someString = (String) field.get(null); // Since the field is static you don't need any instance

Also, beware that using reflection is an expensive and dangerous operation. You should consider redesigning your system

Alberto S.
  • 7,409
  • 6
  • 27
  • 46