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 type)
new Instance
T result = null;
try {
    Constructor<T> constructor = type.getDeclaredConstructor();
    if (!constructor.isAccessible()) {
        constructor.setAccessible(true);
    result = constructor.newInstance();
} catch (RuntimeException rte) {
...
TnewInstance(Class type)
A helper method to create a new instance of a type using the default constructor arguments.
return type.newInstance();
TnewInstance(Class type, Class declarator, Annotation annotation)
new Instance
if (declarator != null)
    try {
        Constructor<?> c = type.getDeclaredConstructor(declarator.getClass(), annotation.annotationType());
        c.setAccessible(true);
        if (c != null)
            return (T) c.newInstance(declarator, annotation);
    } catch (SecurityException e) {
    } catch (NoSuchMethodException e) {
...
TnewInstance(Class type, Class[] parameterTypes, Object[] args)
new Instance
Constructor<T> constructor = getConstructor(type, parameterTypes);
constructor.setAccessible(true);
return constructor.newInstance(args);
TnewInstance(Class type, Object... args)
new Instance
Class<?>[] classArgs = new Class<?>[args.length];
for (int i = 0; i < classArgs.length; i++)
    classArgs[i] = args[i].getClass();
return newInstance(type, classArgs, args);
TnewInstance(Class type, Object... params)
new Instance
return instantiate(type.getName(), findConstructor(type, params), params);
TnewInstance(Constructor c, List parameters)
new Instance
try {
    return (T) c.newInstance(parameters.toArray());
} catch (InstantiationException e) {
    throw new RuntimeException(e);
} catch (IllegalAccessException e) {
    throw new RuntimeException(e);
} catch (IllegalArgumentException e) {
    throw new RuntimeException(e);
...
ObjectnewInstance(Constructor constructor, Object... args)
new Instance
try {
    return constructor.newInstance(args);
} catch (InstantiationException e) {
    throw new IllegalArgumentException("Can't instantiate " + constructor, e);
} catch (IllegalAccessException e) {
    throw new IllegalArgumentException("Can't instantiate " + constructor, e);
} catch (InvocationTargetException e) {
    throw new IllegalArgumentException("Can't instantiate " + constructor, e);
...
ObjectnewInstance(Constructor constructor, Object... arguments)
Fail-safe.
try {
    return constructor.newInstance(arguments);
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
} catch (IllegalArgumentException e) {
} catch (InvocationTargetException e) {
return null;
...
TnewInstance(Constructor ctor, Object... params)
Checked exceptions are LAME.
try {
    return ctor.newInstance(params);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
    throw new RuntimeException(e);