1 /*
2 * Copyright 2011-2020 the original author or authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * https://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.springframework.data.util;
17
18 import java.lang.reflect.Type;
19 import java.lang.reflect.TypeVariable;
20 import java.util.Map;
21
22 import org.springframework.lang.Nullable;
23
24 /**
25 * Base class for {@link TypeInformation} implementations that need parent type awareness.
26 *
27 * @author Oliver Gierke
28 */
29 public abstract class ParentTypeAwareTypeInformation<S> extends TypeDiscoverer<S> {
30
31 private final TypeDiscoverer<?> parent;
32 private int hashCode;
33
34 /**
35 * Creates a new {@link ParentTypeAwareTypeInformation}.
36 *
37 * @param type must not be {@literal null}.
38 * @param parent must not be {@literal null}.
39 */
40 protected ParentTypeAwareTypeInformation(Type type, TypeDiscoverer<?> parent) {
41 this(type, parent, parent.getTypeVariableMap());
42 }
43
44 protected ParentTypeAwareTypeInformation(Type type, TypeDiscoverer<?> parent, Map<TypeVariable<?>, Type> map) {
45
46 super(type, map);
47 this.parent = parent;
48 }
49
50 /*
51 * (non-Javadoc)
52 * @see org.springframework.data.util.TypeDiscoverer#createInfo(java.lang.reflect.Type)
53 */
54 @Override
55 protected TypeInformation<?> createInfo(Type fieldType) {
56
57 if (parent.getType().equals(fieldType)) {
58 return parent;
59 }
60
61 return super.createInfo(fieldType);
62 }
63
64 /*
65 * (non-Javadoc)
66 * @see org.springframework.data.util.TypeDiscoverer#equals(java.lang.Object)
67 */
68 @Override
69 public boolean equals(@Nullable Object obj) {
70
71 if (!super.equals(obj)) {
72 return false;
73 }
74
75 if (obj == null) {
76 return false;
77 }
78
79 if (!this.getClass().equals(obj.getClass())) {
80 return false;
81 }
82
83 ParentTypeAwareTypeInformation<?> that = (ParentTypeAwareTypeInformation<?>) obj;
84 return this.parent == null ? that.parent == null : this.parent.equals(that.parent);
85 }
86
87 /*
88 * (non-Javadoc)
89 * @see org.springframework.data.util.TypeDiscoverer#hashCode()
90 */
91 @Override
92 public int hashCode() {
93
94 if (this.hashCode == 0) {
95 this.hashCode = super.hashCode() + 31 * parent.hashCode();
96 }
97
98 return this.hashCode;
99 }
100 }
101