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

ObjectnewInstance(Class klass)
new Instance
try {
    return klass.newInstance();
} catch (Exception e) {
    throw new RuntimeException(e);
ObjectnewInstance(Class targetClass)
new Instance
Constructor ctor = targetClass.getDeclaredConstructor(EMPTY_CLASS_ARRAY);
ctor.setAccessible(true);
return ctor.newInstance(EMPTY_OBJECT_ARRAY);
ObjectnewInstance(Class cl, Object[] args)
Create an instance of a class cl from constructor with arguments args, even if the constructor is a private constructor.
Class<? extends Object>[] classArray = new Class<?>[args == null ? 0 : args.length];
for (int i = 0; i < args.length; i++) {
    classArray[i] = builtInMap.get(args[i].getClass()) == null ? args[i].getClass()
            : builtInMap.get(args[i].getClass());
Constructor<? extends Object> constructor = cl.getDeclaredConstructor(classArray);
constructor.setAccessible(true);
return constructor.newInstance(args);
...
TnewInstance(Class clazz)
new Instance
try {
    return clazz.newInstance();
} catch (Exception e) {
    throw new RuntimeException("Cant create bean", e);
T[]newInstance(Class componentType, int length)
Creates and returns an array of the given type and size.
return (T[]) Array.newInstance(componentType, length);
ObjectnewInstance(Class classZ)
new Instance
Object instance;
try {
    instance = classZ.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
    logger.error("new instance failure", e);
    throw new RuntimeException(e);
return instance;
...
ObjectnewInstance(Class clazz)
new Instance
if (clazz.isPrimitive()) {
    return primitiveToDefault.get(clazz);
} else if (Calendar.class.isAssignableFrom(clazz)) {
    return Calendar.getInstance();
} else if (clazz.isArray()) {
    Class<?> ct = clazz.getComponentType();
    Object a = Array.newInstance(ct, 1);
    Array.set(a, 0, newInstance(ct));
...
ObjectnewInstance(Class clazz)
new Instance
try {
    return clazz.newInstance();
} catch (InstantiationException e) {
    throw new IllegalStateException("Failed to instantiate the class: " + clazz, e);
} catch (IllegalAccessException e) {
    throw new IllegalStateException("Illegal access to the constructor of the class: " + clazz, e);
ObjectnewInstance(Class clazz)
Tries to invoke Foo.getInstance() if the method (public+static) getInstance() is there; If not, it creates a new instance via reflection.
Object o = getInstance(clazz);
return o == null ? clazz.newInstance() : o;
TnewInstance(Class clazz)
new Instance
try {
    return (T) clazz.newInstance();
} catch (InstantiationException e) {
    throw new RuntimeException(e);
} catch (IllegalAccessException e) {
    throw new RuntimeException(e);