Java Utililty Methods Class New Instance

List of utility methods to do Class New Instance

Description

The list of methods to do Class New Instance are organized into topic(s).

Method

TnewInstance(Class cls)
Creates a new instance of the class.
Constructor constructor;
try {
    constructor = cls.getConstructor();
} catch (NoSuchMethodException e) {
    e.printStackTrace();
    return null;
if (!constructor.isAccessible())
...
TnewInstance(Class cls)
new Instance
Constructor<T> constr = cls.getConstructor((Class[]) null);
if (!constr.isAccessible()) {
    constr.setAccessible(true);
T result = constr.newInstance((Object[]) null);
return result;
TnewInstance(Class cls, Object... args)
Creates a new instance matching possible constructors with provided args.
Constructor<T> declaredConstructor = args.length == 0 ? getConstructor(cls) : getConstructor(cls, args);
boolean accessible = declaredConstructor.isAccessible();
if (accessible) {
    return declaredConstructor.newInstance(args);
} else {
    declaredConstructor.setAccessible(true);
    try {
        return declaredConstructor.newInstance(args);
...
TnewInstance(Class clz, Class argType, K arg)
new Instance
try {
    Constructor<T> cnstr = clz.getDeclaredConstructor(argType);
    cnstr.setAccessible(true);
    return cnstr.newInstance(arg);
} catch (Exception e) {
    throw new RuntimeException(e);
T[]newInstance(Class componentType, int size)
new Instance
return (T[]) Array.newInstance(componentType, size);
T[]newInstance(Class elementType, int len)
Constructs a new array of the given non-primitive component type and length.
if (elementType.isPrimitive()) {
    throw new IllegalArgumentException("element type cannot be primitive: " + elementType);
@SuppressWarnings("unchecked")
T ret[] = (T[]) Array.newInstance(elementType, len);
return ret;
TnewInstance(Class klass)
new Instance
T t = null;
try {
    Constructor<T> constructor = klass.getDeclaredConstructor();
    if (constructor != null) {
        constructor.setAccessible(true);
        t = constructor.newInstance();
} catch (Exception e) {
...
TnewInstance(Class klass)
new Instance
T result;
try {
    Constructor<T> meth = (Constructor<T>) CONSTRUCTOR_CACHE.get(klass);
    if (meth == null) {
        meth = klass.getDeclaredConstructor(new Class[] {});
        meth.setAccessible(true);
        CONSTRUCTOR_CACHE.put(klass, meth);
    result = meth.newInstance();
} catch (Exception e) {
    throw new RuntimeException(e);
return result;
TnewInstance(Class klass)
Creates a new instance of klass .
throw new RuntimeException("ReflectionHelper can't be used from web mode.");
TnewInstance(Class klass)
new Instance
try {
    return (T) klass.newInstance();
} catch (Exception e) {
    throw new IllegalArgumentException("instance class[" + klass.getName() + "] with ex:", e);