1 /*
2 * Copyright 2004-2008 the Seasar Foundation and the Others.
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 * http://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,
13 * either express or implied. See the License for the specific language
14 * governing permissions and limitations under the License.
15 */
16 package org.seasar.uruma.binding.method;
17
18 import java.lang.reflect.Array;
19 import java.lang.reflect.Method;
20
21 import org.seasar.framework.util.MethodUtil;
22 import org.seasar.uruma.core.UrumaMessageCodes;
23 import org.seasar.uruma.exception.UIllegalArgumentException;
24
25 /**
26 * 引数の型を一種類に限定した {@link MethodBinding} クラスです。<br />
27 *
28 * @author y-komori
29 */
30 public class SingleParamTypeMethodBinding extends MethodBinding implements
31 UrumaMessageCodes {
32 private Class<?> paramType;
33
34 /**
35 * {@link SingleParamTypeMethodBinding} を構築します。<br />
36 *
37 * @param target
38 * ターゲットオブジェクト
39 * @param method
40 * ターゲットメソッド
41 * @throws IllegalArgumentException
42 * ターゲットメソッドの引数が2個以上存在する場合
43 */
44 public SingleParamTypeMethodBinding(final Object target, final Method method) {
45 super(target, method, null);
46 setup();
47 }
48
49 /**
50 * {@link SingleParamTypeMethodBinding} を構築します。<br />
51 *
52 * @param target
53 * ターゲットオブジェクト
54 * @param method
55 * ターゲットメソッド
56 * @param callback
57 * コールバックオブジェクト
58 * @throws IllegalArgumentException
59 * ターゲットメソッドの引数が2個以上存在する場合
60 */
61 public SingleParamTypeMethodBinding(final Object target,
62 final Method method, final MethodCallback callback) {
63 super(target, method, callback);
64 setup();
65 }
66
67 private void setup() {
68 Class<?>[] paramTypes = method.getParameterTypes();
69 if (paramTypes.length == 0) {
70 paramType = null;
71 } else if (paramTypes.length == 1) {
72 paramType = paramTypes[0];
73 } else {
74 throw new UIllegalArgumentException(ILLEGAL_ARG_NUMBERS, method
75 .getDeclaringClass().getName(), method.getName());
76 }
77 }
78
79 /*
80 * @see org.seasar.uruma.binding.method.MethodBinding#invoke(java.lang.Object[])
81 */
82 @Override
83 public Object invoke(final Object[] args) {
84 Object[] trueArgs = null;
85 if (paramType != null && args != null) {
86 if (paramType.isArray()) {
87 Class<?> componentType = paramType.getComponentType();
88 Object[] params = (Object[]) Array.newInstance(componentType,
89 args.length);
90 System.arraycopy(args, 0, params, 0, args.length);
91 trueArgs = new Object[] { params };
92 } else {
93 trueArgs = new Object[] { paramType.cast(args[0]) };
94 }
95 }
96
97 Object result = MethodUtil.invoke(method, target, trueArgs);
98 return callback(trueArgs, result);
99 }
100 }