Java Class New Instance newInstance(Class clazz)

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

Description

Constructs a new instance of the class using the no-arg constructor.

License

Apache License

Parameter

Parameter Description
clazz the class of the object

Return

a new instance of the object

Declaration

public static <T> T newInstance(Class<T> clazz) throws InstantiationException, IllegalAccessException,
        SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException 

Method Source Code


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

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Main {
    public static Class<?>[] EMPTY_CLASS_ARRAY = new Class<?>[0];
    public static Object[] EMPTY_OBJECT_ARRAY = new Object[0];

    /**/*from   w w  w . j a v  a  2  s .  c  om*/
     * Constructs a new instance of the class using the no-arg constructor.
     * @param clazz the class of the object
     * @return a new instance of the object
     */
    public static <T> T newInstance(Class<T> clazz) throws InstantiationException, IllegalAccessException,
            SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {

        Constructor<T> cons = getConstructor(clazz);

        return cons.newInstance(EMPTY_OBJECT_ARRAY);
    }

    /**
     * Constructs a new instance of the class using the no-arg constructor.
     * @param classStr the class name of the object
     * @return a new instance of the object
     */
    public static Object newInstance(String classStr)
            throws InstantiationException, IllegalAccessException, ClassNotFoundException, SecurityException,
            IllegalArgumentException, NoSuchMethodException, InvocationTargetException {
        if (classStr == null) {
            throw new IllegalArgumentException("class cannot be null");
        }
        Class<?> clazz = Class.forName(classStr);
        return newInstance(clazz);
    }

    /**
     * Returns the empty argument constructor of the class.
     */
    public static <T> Constructor<T> getConstructor(Class<T> clazz)
            throws SecurityException, NoSuchMethodException {
        if (clazz == null) {
            throw new IllegalArgumentException("class cannot be null");
        }
        Constructor<T> cons = clazz.getConstructor(EMPTY_CLASS_ARRAY);
        cons.setAccessible(true);
        return cons;
    }
}

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, Class[] argumentTypes, Object[] arguments)
  9. newInstance(Class clazz, Class[] parameterTypes, Object[] initargs)