Skip to content

Commit ab96f1e

Browse files
committed
core: Fail fast when values of an incorrect type are set
Helps with #210
1 parent 9f72f1c commit ab96f1e

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

core/src/main/java/org/spongepowered/configurate/ScopedConfigurationNode.java

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
*/
1717
package org.spongepowered.configurate;
1818

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

108114
final @Nullable TypeSerializer<?> serial = options().serializers().get(type);
109115
if (serial != null) {
110116
((TypeSerializer) serial).serialize(type, value, self());
111117
} else if (options().acceptsType(value.getClass())) {
112118
raw(value); // Just write if no applicable serializer exists?
113119
} else {
114-
throw new SerializationException("No serializer available for type " + type);
120+
throw new SerializationException(this, type, "No serializer available for type " + type);
115121
}
116122
return self();
117123
}

core/src/test/java/org/spongepowered/configurate/AbstractConfigurationNodeTest.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -487,4 +487,13 @@ void testMergeToVirtualNode() throws SerializationException {
487487
assertFalse(target.virtual());
488488
}
489489

490+
@Test
491+
void testSetValueOfInvalidType() {
492+
final BasicConfigurationNode root = BasicConfigurationNode.root(ConfigurationOptions.defaults()
493+
.nativeTypes(UnmodifiableCollections.toSet(String.class)));
494+
495+
assertTrue(assertThrows(SerializationException.class, () -> root.set(Integer.class, "hello"))
496+
.getMessage().contains("Got a value of unexpected type"));
497+
}
498+
490499
}

0 commit comments

Comments
 (0)