Skip to content

Commit c9a9b09

Browse files
Copilotozlerhakan
andcommitted
Finalize Java Records support with primitive default values handling
Co-authored-by: ozlerhakan <[email protected]>
1 parent ec1b439 commit c9a9b09

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

src/main/java/com/poiji/util/ReflectUtil.java

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,14 @@ public static <T> T newRecordInstance(Class<T> type, Map<String, Object> recordV
5656
for (int i = 0; i < components.length; i++) {
5757
RecordComponent component = components[i];
5858
parameterTypes[i] = component.getType();
59-
args[i] = recordValues.get(component.getName());
59+
Object value = recordValues.get(component.getName());
60+
61+
// If value is null, use default values for primitives
62+
if (value == null && component.getType().isPrimitive()) {
63+
value = getDefaultValue(component.getType());
64+
}
65+
66+
args[i] = value;
6067
}
6168

6269
Constructor<T> constructor = type.getDeclaredConstructor(parameterTypes);
@@ -69,6 +76,30 @@ public static <T> T newRecordInstance(Class<T> type, Map<String, Object> recordV
6976
}
7077
}
7178

79+
/**
80+
* Returns the default value for a primitive type.
81+
*/
82+
private static Object getDefaultValue(Class<?> type) {
83+
if (type == boolean.class) {
84+
return false;
85+
} else if (type == byte.class) {
86+
return (byte) 0;
87+
} else if (type == short.class) {
88+
return (short) 0;
89+
} else if (type == int.class) {
90+
return 0;
91+
} else if (type == long.class) {
92+
return 0L;
93+
} else if (type == float.class) {
94+
return 0.0f;
95+
} else if (type == double.class) {
96+
return 0.0;
97+
} else if (type == char.class) {
98+
return '\0';
99+
}
100+
return null;
101+
}
102+
72103
/**
73104
* Checks if a class is a record.
74105
*

0 commit comments

Comments
 (0)