View Javadoc

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.util;
17  
18  import java.lang.reflect.Constructor;
19  import java.lang.reflect.InvocationTargetException;
20  
21  import org.seasar.framework.beans.BeanDesc;
22  import org.seasar.framework.beans.factory.BeanDescFactory;
23  import org.seasar.framework.exception.IllegalAccessRuntimeException;
24  import org.seasar.framework.exception.InstantiationRuntimeException;
25  import org.seasar.framework.exception.InvocationTargetRuntimeException;
26  
27  /**
28   * Tiger に対応したクラス用ユーティリティクラスです。<br />
29   * 
30   * @author y-komori
31   */
32  public class ClassUtil {
33      private ClassUtil() {
34  
35      }
36  
37      /**
38       * 新しいインスタンスを生成します。<br />
39       * 
40       * @param <T>
41       *            生成するインスタンスの型
42       * @param clazz
43       *            生成するインスタンスの {@link Class} オブジェクト
44       * @param args
45       *            コンストラクタ引数
46       * @return 生成したインスタンス
47       */
48      @SuppressWarnings("unchecked")
49      public static <T> T newInstance(final Class<? extends T> clazz,
50              final Object... args) {
51          BeanDesc beanDesc = BeanDescFactory.getBeanDesc(clazz);
52          Constructor constructor = beanDesc.getSuitableConstructor(args);
53          Object object = null;
54          try {
55              object = constructor.newInstance(args);
56          } catch (InstantiationException ex) {
57              throw new InstantiationRuntimeException(clazz, ex);
58          } catch (IllegalAccessException ex) {
59              throw new IllegalAccessRuntimeException(clazz, ex);
60          } catch (InvocationTargetException ex) {
61              throw new InvocationTargetRuntimeException(clazz, ex);
62          }
63          return (T) object;
64      }
65  
66      /**
67       * 新しいインスタンスを生成します。<br />
68       * 
69       * @param <T>
70       *            生成するインスタンスの型
71       * @param clazz
72       *            生成するインスタンスの {@link Class} オブジェクト
73       * @return 生成したインスタンス
74       */
75      public static <T> T newInstance(final Class<? extends T> clazz) {
76          return ClassUtil.<T> newInstance(clazz, (Object[]) null);
77      }
78  }