简体   繁体   中英

How to access dynamiclly variables from another Java Class?

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??

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM