1 /*
2 * Copyright 2015-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.projection;
17
18 import lombok.NonNull;
19 import lombok.RequiredArgsConstructor;
20
21 import java.lang.reflect.Method;
22 import java.util.Map;
23
24 import javax.annotation.Nullable;
25
26 import org.aopalliance.intercept.MethodInterceptor;
27 import org.aopalliance.intercept.MethodInvocation;
28 import org.springframework.util.ReflectionUtils;
29
30 /**
31 * {@link MethodInterceptor} to support accessor methods to store and retrieve values from a {@link Map}.
32 *
33 * @author Oliver Gierke
34 * @since 1.10
35 */
36 @RequiredArgsConstructor
37 class MapAccessingMethodInterceptor implements MethodInterceptor {
38
39 private final @NonNull Map<String, Object> map;
40
41 /*
42 * (non-Javadoc)
43 * @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
44 */
45 @Nullable
46 @Override
47 public Object invoke(@SuppressWarnings("null") MethodInvocation invocation) throws Throwable {
48
49 Method method = invocation.getMethod();
50
51 if (ReflectionUtils.isObjectMethod(method)) {
52 return invocation.proceed();
53 }
54
55 Accessor accessor = new Accessor(method);
56
57 if (accessor.isGetter()) {
58 return map.get(accessor.getPropertyName());
59 } else if (accessor.isSetter()) {
60 map.put(accessor.getPropertyName(), invocation.getArguments()[0]);
61 return null;
62 }
63
64 throw new IllegalStateException("Should never get here!");
65 }
66 }
67