Skip to content

Commit

Permalink
#851 Ensure that CompatibleFieldSerializer sets fields with default…
Browse files Browse the repository at this point in the history
… values to `null`
  • Loading branch information
theigl committed Sep 3, 2021
1 parent ee19971 commit 0b2fea2
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ public T read (Kryo kryo, Input input, Class<? extends T> type) {
continue;
}
if (registration == null) {
setFieldToNull(cachedField, object);
if (chunked) inputChunked.nextChunk();
continue;
}
Expand Down Expand Up @@ -242,6 +243,16 @@ else if (compare > 0)
return fields;
}

private void setFieldToNull (CachedField field, Object obj) {
if (field instanceof ReflectField && field.getCanBeNull()) {
try {
((ReflectField)field).set(obj, null);
} catch (IllegalAccessException e) {
throw new KryoException("Error accessing field: " + field, e);
}
}
}

public CompatibleFieldSerializerConfig getCompatibleFieldSerializerConfig () {
return config;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -515,6 +515,20 @@ void testClassWithGenericField () {
roundTrip(9, new ClassWithGenericField<>(1));
}

// https://github.com/EsotericSoftware/kryo/issues/851
@Test
void testClassWithDefaultValueField () {
CompatibleFieldSerializer.CompatibleFieldSerializerConfig config = new CompatibleFieldSerializer.CompatibleFieldSerializerConfig();
config.setChunkedEncoding(true);
config.setReadUnknownFieldData(true);
kryo.setDefaultSerializer(new CompatibleFieldSerializerFactory(config));
kryo.register(ClassWithDefaultValueField.class);

final ClassWithDefaultValueField o = new ClassWithDefaultValueField();
o.setValue(null);
roundTrip(10, o);
}

public static class TestClass {
public String text = "something";
public int moo = 120;
Expand Down Expand Up @@ -811,4 +825,29 @@ public boolean equals (Object o) {
return Objects.equals(value, that.value);
}
}

public static class ClassWithDefaultValueField {

private Integer value = 10;

public Integer getValue () {
return value;
}

public void setValue (Integer value) {
this.value = value;
}

@Override
public boolean equals (Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final ClassWithDefaultValueField that = (ClassWithDefaultValueField)o;
return Objects.equals(value, that.value);
}
}
}

0 comments on commit 0b2fea2

Please sign in to comment.