场景
我有一个类似于 a 类的类变量名称的字符串列表。所以现在我必须使用列表为这些变量设置值。
示例
class Abc {
private String name;
private String Id;
private String sal;
}
public static void main(String args[]){
Map<String,String> variablesMap = new HashMap<String,String>();
variablesMap.add("name","Joshi");
variablesMap.add("id","101");
/*Here i want to write the code to set the values for those variables*/
}
尝试过
类ABC
包含所有getter和setter。
使用 java.lang.Field 类,我可以通过 ABC.class.getDeclaredFileds() 获取变量列表。但之后我该如何设置这些值。
最佳答案
您可以通过 Field field = getClass().getDeclaredField(name); 获取您的名字的
Field
然后查看 Java 文档:Field Documentation 在那里,您有多个选项可以根据数据类型设置变量的值。
看一下这个示例:编辑:更新以适合您的具体问题
import java.lang.reflect.Field;
import java.util.Map;
import java.util.HashMap;
public class FieldTest {
String name;
String id;
public static void main(String[] args) {
new FieldTest();
}
public FieldTest() {
Map<String,String> variablesMap = new HashMap<String,String>();
variablesMap.put("name","Joshi");
variablesMap.put("id","101");
for (Map.Entry<String, String> entry : variablesMap.entrySet())
{
try {
test(entry.getKey(),entry.getValue());
}
catch(NoSuchFieldException ex) {
ex.printStackTrace();
}
catch(IllegalAccessException e) {
e.printStackTrace();
}
}
System.out.println(name);
System.out.println(id);
}
private void test(String name, String value) throws NoSuchFieldException, IllegalAccessException {
Field field = getClass().getDeclaredField(name);
field.set(this,value);
}
}
关于java - 将值设置为名称与字符串数据匹配的类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28580695/