View Javadoc

1   /*
2    * Copyright 2007-2008 Naoki NOSE.
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, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package jp.liq.container.vocabulary;
17  
18  import static jp.liq.container.vocabulary.VocabularyException.Reason.*;
19  import jp.liq.container.reflect.ConstructorWrapper;
20  
21  /**
22   * リフレクション API の Wrapper を生成する static メソッド群です。
23   * 具合が良いように命名されています。
24   * @author nose
25   */
26  public class Ctor {
27  
28      /**
29       * ConstructorWrapper を生成します。
30       * このメソッドは 引数で指定されたクラスにコンストラクタが1つだけ存在するとき、
31       * そのコンストラクタを返します。
32       * @param type コンストラクタを持つ型
33       * @return 生成された ConstructorWrapper
34       * @throws VocabularyException コンストラクタが複数存在する
35       */
36      public <T> ConstructorWrapper<T> of(Class<T> type) 
37              throws VocabularyException {
38          java.lang.reflect.Constructor<?>[] ctors = type.getConstructors();
39          if (ctors.length > 1) {
40              throw new VocabularyException(type,
41                      TOO_MANY_CONSTRUCTOR);
42          }
43          
44          java.lang.reflect.Constructor<T> ctor = null;
45          try {
46              ctor = type.getConstructor(ctors[0].getParameterTypes());
47          } catch (Exception e) {
48              throw new VocabularyException(e, type, 
49                      FAILED_TO_FIND_CONSTRUCTOR);
50          }
51          return new ConstructorWrapper<T>(ctor);
52      }
53  
54      /**
55       * ConstructorWrapper を生成します。
56       * コンストラクタの引数の型を指定することによって、
57       * 取得したいコンストラクタを一意に特定します。
58       * @param type コンストラクタを持つ型
59       * @param args コンストラクタの引数の型
60       * @return 生成されたConstructorWrapper
61       * @throws VocabularyException コンストラクタの取得に失敗
62       */
63      public <T> ConstructorWrapper<T> of(Class<T> type, Class<?>... args) 
64              throws VocabularyException {
65          try {
66              return new ConstructorWrapper<T>(type.getConstructor(args));
67          } catch (Exception e) {
68              throw new VocabularyException(e, type, 
69                      FAILED_TO_FIND_CONSTRUCTOR);
70          }
71      }
72  
73  }