Java Reflection Constructor Invoke invokeConstructor(String className, Object... arguments)

Here you can find the source of invokeConstructor(String className, Object... arguments)

Description

Returns an instantiation of the class specified by the input String using the arguments provided.

License

Open Source License

Parameter

Parameter Description
className a parameter
arguments a parameter

Declaration

public static Object invokeConstructor(String className, Object... arguments) 

Method Source Code


//package com.java2s;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Main {
    /**//  w  ww.j  a  v a 2s  .c  o  m
     * Returns an instantiation of the class specified by the input {@link String} using the
     * arguments provided.
     * 
     * @param className
     * @param arguments
     * @return
     */
    public static Object invokeConstructor(String className, Object... arguments) {
        try {
            Class<?> cls = Class.forName(className);
            Class<?>[] parameterTypes = new Class<?>[arguments.length];
            int i = 0;
            for (Object argument : arguments)
                parameterTypes[i++] = argument.getClass();
            Constructor<?> constructor = cls.getConstructor(parameterTypes);
            if (!constructor.isAccessible())
                constructor.setAccessible(true);
            return constructor.newInstance(arguments);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SecurityException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (IllegalArgumentException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }
}

Related

  1. invokeConstructor(final Class clazz, final Class[] paramTypes, final Object... args)
  2. invokeConstructor(final Constructor constructor, final Object... args)
  3. invokeConstructor(final Constructor constructor, final Object[] args)
  4. invokeConstructor(final Constructor constructor, final Object... args)
  5. invokeConstructor(String className, Class[] paramTypes, Object[] paramValues)
  6. invokeConstructorOrFail(Constructor constructor, Object... args)
  7. invokeCtor(Constructor ctor, String str)
  8. invokeExactConstructor(Class klass, Object arg)
  9. invokePrivateConstructor(Class clazz)