Skip to content

Commit

Permalink
core: Fail fast when values of an incorrect type are set
Browse files Browse the repository at this point in the history
Helps with #210
  • Loading branch information
zml2008 committed Aug 17, 2021
1 parent 9f72f1c commit ab96f1e
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
*/
package org.spongepowered.configurate;

import io.leangen.geantyref.GenericTypeReflector;
import io.leangen.geantyref.TypeToken;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.configurate.serialize.SerializationException;
Expand Down Expand Up @@ -104,14 +105,19 @@ default N set(Type type, @Nullable Object value) throws SerializationException {
if (value == null) {
return set(null);
}
final Class<?> erasedType = GenericTypeReflector.erase(type);
if (!erasedType.isInstance(value)) {
throw new SerializationException(this, type, "Got a value of unexpected type "
+ value.getClass().getName() + ", when the value should be an instance of " + erasedType.getSimpleName());
}

final @Nullable TypeSerializer<?> serial = options().serializers().get(type);
if (serial != null) {
((TypeSerializer) serial).serialize(type, value, self());
} else if (options().acceptsType(value.getClass())) {
raw(value); // Just write if no applicable serializer exists?
} else {
throw new SerializationException("No serializer available for type " + type);
throw new SerializationException(this, type, "No serializer available for type " + type);
}
return self();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -487,4 +487,13 @@ void testMergeToVirtualNode() throws SerializationException {
assertFalse(target.virtual());
}

@Test
void testSetValueOfInvalidType() {
final BasicConfigurationNode root = BasicConfigurationNode.root(ConfigurationOptions.defaults()
.nativeTypes(UnmodifiableCollections.toSet(String.class)));

assertTrue(assertThrows(SerializationException.class, () -> root.set(Integer.class, "hello"))
.getMessage().contains("Got a value of unexpected type"));
}

}

0 comments on commit ab96f1e

Please sign in to comment.