1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.socialsignin.spring.data.dynamodb.repository.support;
17
18 import org.springframework.data.repository.core.support.AbstractEntityInformation;
19 import org.springframework.lang.NonNull;
20 import org.springframework.util.Assert;
21 import org.springframework.util.ReflectionUtils;
22
23 import java.lang.annotation.Annotation;
24 import java.lang.reflect.Field;
25 import java.lang.reflect.Method;
26
27
28
29
30
31
32
33
34
35 public class FieldAndGetterReflectionEntityInformation<T, ID> extends AbstractEntityInformation<T, ID> {
36
37 protected Method method;
38 private Field field;
39
40
41
42
43
44
45
46
47
48
49 public FieldAndGetterReflectionEntityInformation(@NonNull Class<T> domainClass,
50 @NonNull final Class<? extends Annotation> annotation) {
51
52 super(domainClass);
53 Assert.notNull(annotation, "annotation must not be null!");
54
55 ReflectionUtils.doWithMethods(domainClass, (method) -> {
56 if (method.getAnnotation(annotation) != null) {
57 this.method = method;
58 return;
59 }
60 });
61
62 if (method == null) {
63 field = null;
64 ReflectionUtils.doWithFields(domainClass, (field) -> {
65 if (field.getAnnotation(annotation) != null) {
66 this.field = field;
67 return;
68 }
69 });
70 }
71
72 Assert.isTrue(this.method != null || this.field != null,
73 String.format("No field or method annotated with %s found!", annotation.toString()));
74 Assert.isTrue(this.method == null || this.field == null,
75 String.format("Both field and method annotated with %s found!", annotation.toString()));
76
77 if (method != null) {
78 ReflectionUtils.makeAccessible(method);
79 }
80 }
81
82
83
84
85
86
87
88 @Override
89 @SuppressWarnings("unchecked")
90 public ID getId(T entity) {
91 if (method != null) {
92 return entity == null ? null : (ID) ReflectionUtils.invokeMethod(method, entity);
93 } else {
94 return entity == null ? null : (ID) ReflectionUtils.getField(field, entity);
95 }
96 }
97
98
99
100
101
102
103 @Override
104 @SuppressWarnings("unchecked")
105 public Class<ID> getIdType() {
106 return (Class<ID>) (method != null ? method.getReturnType() : field.getType());
107 }
108 }