passing class type as parameter and creating instance of it

newInstance() is Deprecated.

This method propagates any exception thrown by the nullary constructor, including a checked exception. Use of this method effectively bypasses the compile-time exception checking that would otherwise be performed by the compiler. The Constructor.newInstance method avoids this problem by wrapping any exception thrown by the constructor in a (checked) java.lang.reflect.InvocationTargetException.

The deprecated call:

clazz.newInstance()

Can be replaced by:

clazz.getDeclaredConstructor().newInstance()

Example:

void MyMethod(Class type) throws InstantiationException, IllegalAccessException {
    type.getDeclaredConstructor().newInstance();
}

Using reflection to create the instance:

Object obj = clazz.newInstance();

This will use the default no-arg constructor to create the instance.

Constructor<?> constructor = clazz.getConstructor(String.class);
Object object = constructor.newInstance(new Object[] { strArgument });

To create the instance if you have some other constructor which takes arguments.

Tags:

Java

Oop