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

Severity
WARNING
Tags
FragileCode

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 Class#getConstructor() and Constructor#newInstance requires handling three new exceptions: IllegalArgumentException, NoSuchMethodException, and InvocationTargetException.

Suppression

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