将值设置为名称与字符串数据匹配的 class 变量

Set value to a class variable whose name matches to a string data

场景

我有一个字符串列表,它类似于一个 class 的 class 变量的名称。所以现在我必须使用列表为这些变量设置值。

例子

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*/
}

尝试过

Class ABC 包含所有 getter 和 setter。 使用 java.lang.Field class 我可以通过 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);
    }

}

你需要为此使用反射。 说变量 'name' 你有一个方法 getName() in class ABC.

所以, 通过迭代变量映射来创建方法名称。 然后在字符串中获取方法名称,

String nameMethod = "getName";
Object obj=null;
try 
{
  method = getClass().getMethod(nameMethod);
  obj= method.invoke(this);//if blank then method return null for integer and date column
}
catch(NoSuchMethodException e) {

}

您不能按原样使用此代码段,您需要进行一些修改

        //abc is instance of class ABC
        BeanInfo info = Introspector.getBeanInfo(abc.getClass(),Object.class);
        PropertyDescriptor[] props1 = info.getPropertyDescriptors();
        for (PropertyDescriptor pd : props1) {
            String name = pd.getName();
            String arg1 = variablesMap.get(name);
            Method setter = pd.getWriteMethod();
            setter.invoke(abc, arg1);
        }

您必须告诉 Field 要设置以下值的实例:

ABC abc = new ABC();
for (Map.Entry<String, String> entry : variablesMap.entrySet())
    ABC.class.getDeclaredField(entry.getKey()).set(abc, entry.getValue());

您需要使用反射来设置字段的值。

一种选择是使用字段的 set() 方法:

getClass().getDeclaredField(myFieldName).set(myObject, myValue);

如果要使用setter方法设置值,需要生成方法名。并使用 invoke():

设置值
String methodName = "set" + myFieldName.subString(0, 1).toUpperCase() + myFieldName.subString(1);
Method method = getClass().getMethod(methodName, String.class);
method.invoke(myObject, myValue);