Skip to content

Method: apply(Object)

1: /*
2: * JB4JSON-LD
3: * Copyright (C) 2024 Czech Technical University in Prague
4: *
5: * This library is free software; you can redistribute it and/or
6: * modify it under the terms of the GNU Lesser General Public
7: * License as published by the Free Software Foundation; either
8: * version 3.0 of the License, or (at your option) any later version.
9: *
10: * This library is distributed in the hope that it will be useful,
11: * but WITHOUT ANY WARRANTY; without even the implied warranty of
12: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13: * Lesser General Public License for more details.
14: *
15: * You should have received a copy of the GNU Lesser General Public
16: * License along with this library.
17: */
18: package cz.cvut.kbss.jsonld.deserialization.reference;
19:
20: import cz.cvut.kbss.jsonld.common.BeanClassProcessor;
21: import cz.cvut.kbss.jsonld.exception.TargetTypeException;
22:
23: import java.lang.reflect.Field;
24: import java.util.Objects;
25: import java.util.Optional;
26:
27: /**
28: * Represents a singular pending reference.
29: * <p>
30: * That is, a singular attribute referencing an object.
31: */
32: public final class SingularPendingReference implements PendingReference {
33:
34: private final Object targetObject;
35:
36: private final Field targetField;
37:
38: public SingularPendingReference(Object targetObject, Field targetField) {
39: this.targetObject = Objects.requireNonNull(targetObject);
40: this.targetField = Objects.requireNonNull(targetField);
41: }
42:
43: @Override
44: public void apply(Object referencedObject) {
45:• assert referencedObject != null;
46:• if (!targetField.getType().isAssignableFrom(referencedObject.getClass())) {
47: throw new TargetTypeException(
48: "Cannot assign referenced object " + referencedObject + " of type " + referencedObject
49: .getClass() + " to field " + targetField);
50: }
51: BeanClassProcessor.setFieldValue(targetField, targetObject, referencedObject);
52: }
53:
54: @Override
55: public Optional<Class<?>> getTargetType() {
56: return Optional.of(targetField.getType());
57: }
58:
59: @Override
60: public boolean equals(Object o) {
61: if (this == o) {
62: return true;
63: }
64: if (o == null || getClass() != o.getClass()) {
65: return false;
66: }
67: SingularPendingReference that = (SingularPendingReference) o;
68: return targetObject.equals(that.targetObject) && targetField.equals(that.targetField);
69: }
70:
71: @Override
72: public int hashCode() {
73: return Objects.hash(targetObject, targetField);
74: }
75: }