Skip to content

Method: trySettingReferenceToKnownInstance(Field, Object)

1: package cz.cvut.kbss.jsonld.deserialization;
2:
3: import cz.cvut.kbss.jsonld.common.BeanClassProcessor;
4: import cz.cvut.kbss.jsonld.deserialization.util.DataTypeTransformer;
5: import cz.cvut.kbss.jsonld.exception.JsonLdDeserializationException;
6:
7: import java.lang.reflect.Field;
8: import java.util.Collection;
9: import java.util.Map;
10:
11: class SingularObjectContext<T> extends InstanceContext<T> {
12:
13: private final Map<String, Field> fieldMap;
14:
15: SingularObjectContext(T instance, Map<String, Field> fieldMap, Map<String, Object> knownInstances) {
16: super(instance, knownInstances);
17: this.fieldMap = fieldMap;
18: }
19:
20: @Override
21: Field getFieldForProperty(String property) {
22: // TODO Add handling of @Properties
23: return fieldMap.get(property);
24: }
25:
26: @Override
27: void setFieldValue(Field field, Object value) {
28: assert !(instance instanceof Collection);
29: if (!field.getType().isAssignableFrom(value.getClass())) {
30: boolean success = trySettingReferenceToKnownInstance(field, value);
31: if (success) {
32: return;
33: }
34: success = tryTypeTransformation(field, value);
35: if (success) {
36: return;
37: }
38: throw valueTypeMismatch(value, field);
39: }
40: BeanClassProcessor.setFieldValue(field, instance, value);
41: }
42:
43: private JsonLdDeserializationException valueTypeMismatch(Object value, Field field) {
44: return new JsonLdDeserializationException(
45: "Type mismatch. Cannot set value " + value + " of type " + value.getClass() + " on field " + field);
46: }
47:
48: private boolean trySettingReferenceToKnownInstance(Field field, Object value) {
49:• if (!knownInstances.containsKey(value.toString())) {
50: return false;
51: }
52: final Object knownInstance = knownInstances.get(value.toString());
53:• if (!field.getType().isAssignableFrom(knownInstance.getClass())) {
54: // Throw the exception right here so that it contains info about the known instance's type
55: throw valueTypeMismatch(knownInstance, field);
56: }
57: BeanClassProcessor.setFieldValue(field, instance, knownInstance);
58: return true;
59: }
60:
61: private boolean tryTypeTransformation(Field field, Object value) {
62: final Class<?> targetType = field.getType();
63: final Object transformedValue = DataTypeTransformer.transformValue(value, targetType);
64: if (transformedValue != null) {
65: BeanClassProcessor.setFieldValue(field, instance, transformedValue);
66: return true;
67: }
68: return false;
69: }
70: }