File: ClassNewInstance.md

package info (click to toggle)
error-prone-java 2.18.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 23,204 kB
  • sloc: java: 222,992; xml: 1,319; sh: 25; makefile: 7
file content (23 lines) | stat: -rw-r--r-- 1,300 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
The documentation for [`Class#newInstance`][javadoc] includes the following
warning:

[javadoc]: https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#newInstance

> 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](https://bugs.openjdk.java.net/browse/JDK-6850612).

Note that migrating to `Class#getConstructor()` and `Constructor#newInstance`
requires handling three new exceptions: [`IllegalArgumentException`][iae],
[`NoSuchMethodException`][nsme], and [`InvocationTargetException`][ite].

[iae]: https://docs.oracle.com/javase/8/docs/api/java/lang/IllegalArgumentException.html
[ite]: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/InvocationTargetException.html
[nsme]: https://docs.oracle.com/javase/8/docs/api/java/lang/NoSuchMethodException.html