DATACMNS-1200 - Fix entity instantiation of Kotlin types using primitives with default values.

We now determine initial values for primitive parameters in Kotlin constructors that are absent (null) and defaulted. We default all Java primitive types to their initial zero value to prevent possible NullPointerExceptions. Kotlin defaulting uses a bitmask to determine which parameter should be defaulted but still requires the appropriate type.

Previously, null values were attempted to cast/unbox and caused NullPointerException even though they had default values through Kotlin assigned.

Original pull request: #255.
This commit is contained in:
Mark Paluch
2017-10-18 15:12:38 +02:00
committed by Oliver Gierke
parent 506fe37aea
commit cf5af6a971
2 changed files with 69 additions and 4 deletions

View File

@@ -229,15 +229,19 @@ public class KotlinClassGeneratingEntityInstantiator extends ClassGeneratingEnti
int slot = i / 32;
int offset = slot * 32;
Object param = provider.getParameterValue(parameters.get(i));
Parameter<Object, P> parameter = parameters.get(i);
Class<Object> type = parameter.getType().getType();
Object param = provider.getParameterValue(parameter);
KParameter kParameter = kParameters.get(i);
// what about null and parameter is mandatory? What if parameter is non-null?
if (kParameter.isOptional()) {
if (kParameter.isOptional() && param == null) {
if (param == null) {
defaulting[slot] = defaulting[slot] | (1 << (i - offset));
defaulting[slot] = defaulting[slot] | (1 << (i - offset));
if (type.isPrimitive()) {
param = getPrimitiveDefault(type);
}
}
@@ -251,5 +255,42 @@ public class KotlinClassGeneratingEntityInstantiator extends ClassGeneratingEnti
return params;
}
private static Object getPrimitiveDefault(Class<?> type) {
if (type == Byte.TYPE || type == Byte.class) {
return (byte) 0;
}
if (type == Short.TYPE || type == Short.class) {
return (short) 0;
}
if (type == Integer.TYPE || type == Integer.class) {
return 0;
}
if (type == Long.TYPE || type == Long.class) {
return 0L;
}
if (type == Float.TYPE || type == Float.class) {
return 0F;
}
if (type == Double.TYPE || type == Double.class) {
return 0D;
}
if (type == Character.TYPE || type == Character.class) {
return '\u0000';
}
if (type == Boolean.TYPE) {
return Boolean.FALSE;
}
throw new IllegalArgumentException(String.format("Primitive type %s not supported!", type));
}
}
}