Skip to content

Commit

Permalink
feat: add better type support for java records
Browse files Browse the repository at this point in the history
  • Loading branch information
jonas-grgt committed Mar 1, 2024
1 parent 123a0f4 commit b8fe1f5
Show file tree
Hide file tree
Showing 3 changed files with 498 additions and 6 deletions.
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
package io.jonasg.xjx.serdes.deserialize;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class RecordWrapper<T> {
private final Map<String, Object> fieldMapping = new HashMap<>();

private final Class<T> type;

public RecordWrapper(Class<T> type) {
Expand All @@ -17,6 +17,7 @@ public void set(String name, Object value) {
this.fieldMapping.put(name, value);
}

@SuppressWarnings("unchecked")
public T record() {
try {
Constructor<?>[] constructors = type.getDeclaredConstructors();
Expand All @@ -28,13 +29,36 @@ public T record() {
var parameters = constructor.getParameters();
for (int i = 0; i < parameters.length; i++) {
String paramName = parameters[i].getName();
args[i] = fieldMapping.getOrDefault(paramName, null);
Class<?> paramType = parameters[i].getType();
Object paramValue = fieldMapping.get(paramName);
if (paramValue != null) {
args[i] = paramValue;
}
else {
if (paramType == boolean.class) {
args[i] = false;
}
else if (paramType == long.class) {
args[i] = 0;
}
else if (paramType == double.class) {
args[i] = 0;
}
else if (paramType == char.class) {
args[i] = '\000';
}
else {
args[i] = null;
}
}
}

return (T) constructor.newInstance(args);

} catch (Exception e) {
}
catch (Exception e) {
throw new RuntimeException("Error creating record", e);
}
}

}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package io.jonasg.xjx.serdes.deserialize.accessor;

import io.jonasg.xjx.serdes.TypeMappers;
import io.jonasg.xjx.serdes.deserialize.RecordWrapper;
import io.jonasg.xjx.serdes.reflector.FieldReflector;

Expand All @@ -16,6 +17,7 @@ public RecordFieldAccessor(FieldReflector field, RecordWrapper recordWrapper) {

@Override
public void set(Object value) {
recordWrapper.set(field.rawField().getName(), value);
Object mappedValue = TypeMappers.forType(field.type()).apply(value);
recordWrapper.set(field.rawField().getName(), mappedValue);
}
}
Loading

0 comments on commit b8fe1f5

Please sign in to comment.