Here you can find the source of newInstance(Class
Parameter | Description |
---|---|
c | class to instantiate |
T | instantiated type |
Parameter | Description |
---|---|
IllegalArgumentException | if c has no no-arg constructor |
public static <T> T newInstance(Class<T> c)
//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); } } }