1 /*
2 * Copyright 2016-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 java.beans.PropertyDescriptor;
19 import java.lang.reflect.Method;
20
21 import org.springframework.beans.BeanUtils;
22 import org.springframework.util.Assert;
23
24 /**
25 * Helper value to abstract an accessor.
26 *
27 * @author Oliver Gierke
28 * @author Christoph Strobl
29 * @soundtrack Benny Greb - Soulfood (Live)
30 * @since 1.13
31 */
32 public final class Accessor {
33
34 private final PropertyDescriptor descriptor;
35 private final Method method;
36
37 /**
38 * Creates an {@link Accessor} for the given {@link Method}.
39 *
40 * @param method must not be {@literal null}.
41 * @throws IllegalArgumentException in case the given method is not an accessor method.
42 */
43 public Accessor(Method method) {
44
45 Assert.notNull(method, "Method must not be null!");
46
47 PropertyDescriptor descriptor = BeanUtils.findPropertyForMethod(method);
48
49 if (descriptor == null) {
50 throw new IllegalArgumentException(String.format("Invoked method %s is no accessor method!", method));
51 }
52
53 this.descriptor = descriptor;
54 this.method = method;
55 }
56
57 /**
58 * Returns whether the accessor is a getter.
59 *
60 * @return
61 */
62 public boolean isGetter() {
63 return method.equals(descriptor.getReadMethod());
64 }
65
66 /**
67 * Returns whether the accessor is a setter.
68 *
69 * @return
70 */
71 public boolean isSetter() {
72 return method.equals(descriptor.getWriteMethod());
73 }
74
75 /**
76 * Returns the name of the property this accessor handles.
77 *
78 * @return will never be {@literal null}.
79 */
80 public String getPropertyName() {
81 return descriptor.getName();
82 }
83 }
84