use of com.robo4j.socket.http.dto.ClassGetSetDTO in project robo4j by Robo4J.
the class ReflectUtils method createInstanceByClazzAndDescriptorAndJsonDocument.
@SuppressWarnings("unchecked")
public static <T> T createInstanceByClazzAndDescriptorAndJsonDocument(Class<T> clazz, JsonDocument jsonDocument) {
try {
Object instance = clazz.getDeclaredConstructor().newInstance();
getFieldsTypeMap(clazz).entrySet().stream().filter(e -> Objects.nonNull(jsonDocument.getKey(e.getKey()))).forEach(e -> {
try {
ClassGetSetDTO value = e.getValue();
if (value.getValueClass().isEnum()) {
if (e.getValue().getCollection() != null) {
switch(e.getValue().getCollection()) {
case LIST:
List<Enum<?>> enumList = ((JsonDocument) jsonDocument.getKey(e.getKey())).getArray().stream().map(el -> extractEnumConstant(el.toString(), (Enum<?>[]) value.getValueClass().getEnumConstants())).collect(Collectors.toCollection(LinkedList::new));
value.getSetMethod().invoke(instance, enumList);
break;
case MAP:
throw new IllegalStateException("not implemented");
default:
throw new IllegalStateException("not allowed");
}
} else {
value.getSetMethod().invoke(instance, extractEnumConstant(jsonDocument.getKey(e.getKey()).toString(), (Enum<?>[]) value.getValueClass().getEnumConstants()));
}
} else {
value.getSetMethod().invoke(instance, adjustRoboJsonDocumentCast(value, jsonDocument, e.getKey()));
}
} catch (Exception e1) {
throw new RoboReflectException("create instance field", e1);
}
});
return (T) instance;
} catch (Exception e) {
throw new RoboReflectException("create instance with setter", e);
}
}
use of com.robo4j.socket.http.dto.ClassGetSetDTO in project robo4j by Robo4J.
the class ReflectUtils method castObjectByRoboJsonDocument.
@SuppressWarnings("unchecked")
private static <T> T castObjectByRoboJsonDocument(Class<T> clazz, Object value) {
if (clazz.equals(String.class) || WITHOUT_QUOTATION_TYPES.contains(clazz)) {
return (T) adjustRoboClassCast(clazz, value);
} else {
try {
Object instance = clazz.getDeclaredConstructor().newInstance();
Map<String, ClassGetSetDTO> fieldNameMethods = getFieldsTypeMap(clazz);
JsonDocument document = (JsonDocument) value;
fieldNameMethods.forEach((k, v) -> {
Object setValue = adjustRoboClassCast(v.getValueClass(), document.getKey(k));
try {
v.getSetMethod().invoke(instance, setValue);
} catch (Exception e) {
throw new RoboReflectException("set value", e);
}
});
return (T) instance;
} catch (Exception e) {
throw new RoboReflectException("casting: new class instance", e);
}
}
}
Aggregations