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(String clazzStr)
new Instance
try {
    Class<?> clazz = loadClass(clazzStr);
    return instantiate(clazz);
} catch (Exception ex) {
return null;
TnewInstance(String cls, Class interfaceType)
new Instance
Class<?> clazz;
try {
    clazz = Class.forName(cls);
} catch (ClassNotFoundException e) {
    throw new IllegalArgumentException("class not found: " + cls, e);
Object obj;
try {
...
ObjectnewInstance(String klass)
new Instance
try {
    Class c = Class.forName(klass);
    return c.newInstance();
} catch (Exception e) {
    throw new RuntimeException(e);
ObjectnewInstance(String name)
new Instance
try {
    return forName(name).newInstance();
} catch (InstantiationException e) {
    throw new IllegalStateException(e.getMessage(), e);
} catch (IllegalAccessException e) {
    throw new IllegalStateException(e.getMessage(), e);
ObjectnewInstance(String name, ClassLoader loader)
new Instance
return newInstance(forName(name, loader));
ObjectnewInstance(String s)
Creates a new instance of the given class.
final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
try {
    Class clazz = classLoader.loadClass(s);
    Constructor constructor = clazz.getConstructor();
    return constructor.newInstance();
} catch (ClassNotFoundException e) {
    return null;
} catch (IllegalAccessException e) {
...
ObjectnewInstance(String type)
new Instance
Object object = Class.forName(type).newInstance();
return object;
TnewInstance(String type, Class cast)
new Instance
return forName(type, cast).newInstance();
TnewInstance(T obj)
Generic newInstance that tries to clone an object.
try {
    Object n = obj.getClass().getConstructor().newInstance();
    return (T) n;
} catch (NullPointerException e) {
    throw new IllegalArgumentException("Null pointer exception in newInstance()", e);
TnewInstance(T obj, Class argType, Object arg)
new Instance
Object newObj = obj.getClass().getConstructor(argType).newInstance(arg);
return (T) newObj;