Java Class New Instance newInstance(Class c)

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

Description

Instances a new instance of c .

License

Open Source License

Parameter

Parameter Description
c class to instantiate
T instantiated type

Exception

Parameter Description
IllegalArgumentException if c has no no-arg constructor

Return

new T

Declaration

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

Method Source Code


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

import java.lang.reflect.Constructor;

import java.lang.reflect.InvocationTargetException;

public class Main {
    /**/* w w  w  . ja v  a2  s  .  com*/
     * Instances a new instance of {@code c}.
     * @param c class to instantiate
     * @param <T> instantiated type
     * @return new {@code T}
     * @throws IllegalArgumentException if {@code c} has no no-arg constructor
     */
    public static <T> T newInstance(Class<T> c) {
        try {
            Constructor<T> noArgConstructor = c.getDeclaredConstructor();
            noArgConstructor.setAccessible(true);

            return noArgConstructor.newInstance();
        } catch (NoSuchMethodException e) {
            throw new IllegalArgumentException(c + " does not provide a no-arg constructor");
        } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }
}

Related

  1. newInstance(Class theClass, Class expected)
  2. newInstance(Class interfaceDefinition, String className, ClassLoader classLoader)
  3. newInstance(Class aClass, Object... args)
  4. newInstance(Class arrayComponentClass, T value)
  5. newInstance(Class beanClass)
  6. newInstance(Class c)
  7. newInstance(Class c, Class[] argTypes, Object[] args)
  8. newInstance(Class cl)
  9. newInstance(Class classOf)