Java Reflection Constructor Invoke invokeConstructor(Class clazz, Object... parameters)

Here you can find the source of invokeConstructor(Class clazz, Object... parameters)

Description

invoke Constructor

License

Open Source License

Declaration

public static Object invokeConstructor(Class<?> clazz, Object... parameters) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.lang.reflect.*;

public class Main {
    public static Object invokeConstructor(Class<?> clazz, Object... parameters) {
        try {//from ww w. j  a v  a 2  s  .  co m
            Constructor constructor = clazz.getConstructor(convertToMethodParameters(parameters));
            return constructor.newInstance(parameters);
        } catch (NoSuchMethodException | InstantiationException | IllegalAccessException
                | InvocationTargetException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static Class<?>[] convertToMethodParameters(Object... parameters) {
        Class<?>[] classes = new Class<?>[parameters.length];
        for (int i = 0; i < parameters.length; i++) {
            Class<?> clazz = parameters[i].getClass();
            if (clazz == Boolean.class) {
                clazz = boolean.class;
            } else if (clazz == Byte.class) {
                clazz = byte.class;
            } else if (clazz == Character.class) {
                clazz = char.class;
            } else if (clazz == Double.class) {
                clazz = double.class;
            } else if (clazz == Float.class) {
                clazz = float.class;
            } else if (clazz == Integer.class) {
                clazz = int.class;
            } else if (clazz == Long.class) {
                clazz = long.class;
            } else if (clazz == Short.class) {
                clazz = short.class;
            } else if (clazz == Void.class) {
                clazz = void.class;
            }
            classes[i] = clazz;
        }
        return classes;
    }

    private static Class<?> getClass(String clazz) {
        try {
            return Class.forName(clazz);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }
}

Related

  1. invoke(Constructor constructor)
  2. invoke(Constructor constructor, Object... args)
  3. invoke(Constructor constructor, Object... args)
  4. invokeConstructor(Class clazz, Class[] paramTypes, Object[] params)
  5. invokeConstructor(Class objectClass, Class[] classes, Object... params)
  6. invokeConstructor(Class clazz, Class[] argTypes, Object[] args)
  7. invokeConstructor(Class cls)
  8. invokeConstructor(Class type, Object value)