ClassNewInstance
Class.newInstance() bypasses exception checking; prefer getDeclaredConstructor().newInstance()

Category
Severity
WARNING
Maturity

The problem

The documentation for Class#newInstance includes the following warning:

Note that 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) InvocationTargetException.

Always prefer myClass.getConstructor().newInstance() to calling myClass.newInstance() directly. The Class#newInstance method is slated for deprecation in JDK 9.

Note that migrating to Constructor#newInstance requires handling two new exceptions: IllegalArgumentException and InvocationTargetException.

Suppression

Suppress false positives by adding an @SuppressWarnings("ClassNewInstance") annotation to the enclosing element.