Java Class New Instance newInstance(Class clazz)

Here you can find the source of newInstance(Class clazz)

Description

new Instance

License

Apache License

Declaration

public static Object newInstance(Class<?> clazz) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.lang.reflect.InvocationTargetException;

import java.util.Arrays;

import java.util.List;

public class Main {
    private static final Object[] EMPTY_PARAMS = new Object[] {};

    public static Object newInstance(Class<?> clazz) {
        return newInstance(clazz, EMPTY_PARAMS);
    }/*from ww w . j a  v  a 2  s  .c om*/

    public static Object newInstance(Class<?> clazz, Object... params) {
        try {
            if (params.length < 0) {
                return clazz.newInstance();
            }
            return clazz.getDeclaredConstructor(getParamsClass(Arrays.asList(params))).newInstance(params);
        } catch (InstantiationException e) {
            throw new RuntimeException(
                    String.format("Unable to instantiate class (s%) with (%s) constructor parameters",
                            clazz.getCanonicalName(), params.length),
                    e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(
                    String.format("Unable to access constructor with (%s) parameters", params.length), e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(
                    String.format("Unable to find constructor with the provided params, class (%s)",
                            clazz.getCanonicalName()),
                    e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(
                    String.format("Unable to find constructor with the provided params, class (%s)",
                            clazz.getCanonicalName()),
                    e);
        }
    }

    /**
     * Returns an arrays of classes for the given params
     * @param params
     * @return
     */
    public static Class<?>[] getParamsClass(List<?> params) {
        final Class<?>[] classes = new Class<?>[params.size()];
        for (int i = 0; i < classes.length; i++) {
            classes[i] = params.get(i).getClass();
        }
        return classes;
    }
}

Related

  1. newInstance(Class clazz)
  2. newInstance(Class clazz)
  3. newInstance(Class clazz)
  4. newInstance(Class clazz)
  5. newInstance(Class clazz)
  6. newInstance(Class clazz, Class[] args, Object[] objects)
  7. newInstance(Class clazz, Object... args)
  8. newInstance(Class clazz, Object... args)
  9. newInstance(Class cls)