Как внедрить карту пар ключ-значение в объект только с Core Java? - PullRequest
1 голос
/ 14 января 2020

Как я могу вставить карту в объект, используя только Core Java?

У меня есть карта с 4 парами ключ-значение (String, Object) и класс с 3 полями, я хочу вызовите метод установки на основе имени ключа и установите их.

{
 "variableA": "A",
 "variableB": true,
 "variableC": 1,
 "variableD": "DONT USE"
}

public Class Example {
  public void setVaraibleA(String variableA);
  public void setVaraibleB(Boolean variableB);
  public void setVaraibleC(Integer variableC);
}

Example example = new Example();
// Do something to map it
assert(example.getVariableA.equals("A"));
assert(example.getVariableB.equals(true));
assert(example.getVariableC.equals(1));

Ответы [ 2 ]

1 голос
/ 14 января 2020

вы можете использовать Java Reflection, чтобы получить метод (с указанием его имени) и вызвать его с данным параметром.

Example example = new Example();
Method method = Example.class.getMethod("setVariableA", String.class);

method.invoke(example, "parameter-value1");
0 голосов
/ 14 января 2020

Вместо ответа @ Beppe C, если вы не можете легко определить тип объекта, который вы вводите во время выполнения, и предполагая, что у вас нет повторяющихся имен свойств, я бы использовал метод класса getMethods() и метод метода getName().

В основном я написал бы такой код, подобный следующему:

Method[] exampleMethods = Example.class.getMethods();
Map<String, Method> setterMethodsByPropertyName = new HashMap<>(exampleMethods.length);
for (Method exampleMethod : exampleMethods) {
  String methodName = exampleMethod.getName();
  if (!methodName.startsWith("set")) {
    continue;
  }
  // substring starting right after "set"
  String variableName = methodName.substring(3);
  // use lowercase here because:
  // 1. JSON property starts with lower case but setter name after "set" starts with upper case
  // 2. property names should all be different so no name conflict (assumption)
  String lcVariableNmae = variableName.toLowerCase();
  setterMethodsByPropertyName.put(lcVariableName, exampleMethod);
}

// later in the code, and assuming that your JSON map is accessible via a Java Map
for (Map.Entry<String, ?> entry : jsonMap.entrySet()) {
  String propertyName = entry.getKey();
  String lcPropertyName = propertyName.toLowerCase();
  if(!setterMethodsByPropertyName.containsKey(lcPropertyName)) {
    // do something for this error condition where the property setter can't be found
  }
  Object propertyValue = entry.getValue();
  Method setter = setterMethodsByPropertyName.get(lcPropertyName);
  setter.invoke(myExampleInstance, propertyValue);
}
...