Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/hadoop/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java通过变量调用类属性_Java_Reflection - Fatal编程技术网

java通过变量调用类属性

java通过变量调用类属性,java,reflection,Java,Reflection,我想通过变量调用类属性。 例如 Billing.SKU_NAME_PREMIUM1 我想: String a = 'SKU_NAME_PREMIUM1'; Billing.a 编辑: 我想在中使用变量作为属性名 SharedPreferences.Editor editor = shared.edit(); editor.putBoolean(Billing.KEY_PREMIUM_VERSION, true); 因为类Billing有30多个属性,并根据用户的选择在运行时选择该属性。

我想通过变量调用类属性。 例如

Billing.SKU_NAME_PREMIUM1
我想:

String a = 'SKU_NAME_PREMIUM1';
Billing.a
编辑:

我想在中使用变量作为属性名

 SharedPreferences.Editor editor = shared.edit();
 editor.putBoolean(Billing.KEY_PREMIUM_VERSION, true);
因为类Billing有30多个属性,并根据用户的选择在运行时选择该属性。注意:不建议在产品/最终代码中使用反射

Object o = ...;
Field f = o.getClass().getField("a");

看起来您正在查找变量。现在假设KEY\u PREMIUM\u版本的类型为int,我们可以使用

SharedPreferences.Editor editor = shared.edit();
int ver = Billing.KEY_PREMIUM_VERSION;//variable `ver` will 
                                      //copy value of Billing.KEY_PREMIUM_VERSION
editor.putBoolean(ver, true);

这在Java中是不可能的,但可能有一些解决方法。你为什么需要它?也许映射就是您想要的?您是否需要这种精确的行为或类似Building.getValuea或Utils.getValuea之类的行为?可以接受Building?我想在SharedReferences中使用变量作为属性名。Editor=shared.edit;editor.putBooleanBilling.KEY_PREMIUM_版本,true;要在问题中添加更多信息,请使用帖子下方的选项。