Java Class New Instance newInstance(Class clazz)

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

Description

new Instance

License

Open Source License

Declaration

public static <T> T newInstance(Class<T> clazz) 

Method Source Code

//package com.java2s;

public class Main {

    @SuppressWarnings("unchecked")
    public static <T> T newInstance(String clazz) {
        try {/*from   w  w  w  .  j ava2  s  .c  om*/
            return (T) Class.forName(clazz).newInstance();
        } catch (Exception e) {
            throw new RuntimeException("Instance class " + clazz + " error!");
        }
    }

    public static <T> T newInstance(Class<T> clazz) {
        try {
            return (T) clazz.newInstance();
        } catch (Exception e) {
            throw new RuntimeException("Instance class " + clazz + " error!");
        }
    }

    public static <T> T newInstance(Class<T> clazz, Object... params) {
        if (null == params || 0 == params.length) {
            return newInstance(clazz);
        }

        try {
            return clazz.getDeclaredConstructor(getClasses(params)).newInstance(params);
        } catch (Exception e) {
            throw new RuntimeException("Instance class " + clazz + " error!", e);
        }
    }

    public static Class<?>[] getClasses(Object... objects) {
        Class<?>[] classes = new Class<?>[objects.length];
        for (int i = 0; i < objects.length; i++) {
            classes[i] = objects[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)
  7. newInstance(Class clazz)
  8. newInstance(Class clazz)
  9. newInstance(Class clazz, Class[] argumentTypes, Object[] arguments)