01 /*
02 * Copyright 2008-2017 the original author or authors.
03 *
04 * Licensed under the Apache License, Version 2.0 (the "License");
05 * you may not use this file except in compliance with the License.
06 * You may obtain a copy of the License at
07 *
08 * http://www.apache.org/licenses/LICENSE-2.0
09 *
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.codehaus.griffon.runtime.core.configuration;
17
18 import org.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
20
21 import javax.annotation.Nonnull;
22 import java.lang.reflect.InvocationTargetException;
23 import java.lang.reflect.Method;
24
25 import static griffon.core.GriffonExceptionHandler.sanitize;
26 import static java.util.Objects.requireNonNull;
27
28 /**
29 * @author Andres Almiray
30 * @since 2.11.0
31 */
32 public class MethodInjectionPoint extends InjectionPoint {
33 private static final Logger LOG = LoggerFactory.getLogger(FieldInjectionPoint.class);
34
35 private final Method writeMethod;
36 private final Class type;
37
38 public MethodInjectionPoint(@Nonnull Method writeMethod, @Nonnull String configuration, @Nonnull String key, @Nonnull String format) {
39 super(configuration, key, format);
40 this.writeMethod = requireNonNull(writeMethod, "Argument 'writeMethod' must not be null");
41 this.type = writeMethod.getParameterTypes()[0];
42 }
43
44 @Nonnull
45 public Method getWriteMethod() {
46 return writeMethod;
47 }
48
49 public void setValue(@Nonnull Object instance, Object value) {
50 requireNonNull(instance, "Argument 'instance' must not be null");
51 try {
52 writeMethod.invoke(instance, value);
53 } catch (IllegalAccessException | InvocationTargetException e) {
54 if (LOG.isWarnEnabled()) {
55 LOG.warn("Cannot set value on method " + getConfiguration() + "() of instance " + instance, sanitize(e));
56 }
57 }
58 }
59
60 @Nonnull
61 public Class<?> getType() {
62 return type;
63 }
64
65 @Override
66 public String toString() {
67 final StringBuilder sb = new StringBuilder("MethodInjectionPoint{");
68 sb.append("writeMethod=").append(writeMethod);
69 sb.append(", type=").append(type);
70 sb.append(", configuration='").append(getConfiguration()).append('\'');
71 sb.append(", key='").append(getKey()).append('\'');
72 sb.append(", format='").append(getFormat()).append('\'');
73 sb.append('}');
74 return sb.toString();
75 }
76 }
|