View Javadoc

1   package com.atlassian.core.util;
2   
3   import com.atlassian.core.util.ClassLoaderUtils;
4   
5   import java.lang.reflect.Constructor;
6   import java.lang.reflect.InvocationTargetException;
7   
8   public class ClassHelper
9   {
10      public static Object instantiateClass(Class clazz, Object[] constructorArgs) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException
11      {
12          Class args[] = new Class[constructorArgs.length];
13          for (int i = 0; i < constructorArgs.length; i++)
14          {
15              if (constructorArgs == null)
16              {
17                  args[i] = null;
18              }
19              else
20              {
21                  args[i] = constructorArgs[i].getClass();
22              }
23          }
24          Constructor ctor = null;
25          if (clazz.getConstructors().length == 1)
26          {
27              ctor = clazz.getConstructors()[0];
28          } else {
29              //Obtaioning the ctor this way the class types need to be an exact match
30              //We could obtain the required behaviour by checkinng that our args are assignable
31              //for a given ctor... but I can't be bothered right now
32              ctor = clazz.getConstructor(args);
33          }
34          return ctor.newInstance(constructorArgs);
35      }
36  
37      public static Object instantiateClass(String name, Object[] constructorArgs) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException
38      {
39          Class clazz = ClassLoaderUtils.loadClass(name, ClassHelper.class);
40          return instantiateClass(clazz, constructorArgs);
41      }
42  }