|
| 1 | +--- |
| 2 | +id: da4d528e-40f5-4a65-be86-ed01776ce458 |
| 3 | +slug: "class-newinstance-to-constructor" |
| 4 | +title: "Class.newInstance() to constructor reflection" |
| 5 | +category: "tooling" |
| 6 | +difficulty: "intermediate" |
| 7 | +jdkVersion: "9" |
| 8 | +oldLabel: "Deprecated Class.newInstance()" |
| 9 | +modernLabel: "Constructor reflection" |
| 10 | +oldApproach: "Class.newInstance()" |
| 11 | +modernApproach: "Explicit constructor lookup" |
| 12 | +oldCode: |- |
| 13 | + Plugin plugin = pluginClass.newInstance(); |
| 14 | +modernCode: |- |
| 15 | + Plugin plugin = pluginClass |
| 16 | + .getDeclaredConstructor() |
| 17 | + .newInstance(); |
| 18 | +summary: "Replace deprecated Class.newInstance() with explicit constructor lookup and invocation." |
| 19 | +explanation: "Class.newInstance() is deprecated because it can bypass compile-time checking for exceptions thrown by the constructor and only supports a zero-argument constructor. Explicit Constructor lookup makes the selected signature visible and reports reflective invocation failures through the appropriate reflection exceptions. Module and access rules still apply; this pattern does not recommend bypassing encapsulation." |
| 20 | +whyModernWins: |
| 21 | +- icon: "✅" |
| 22 | + title: "Supported API" |
| 23 | + desc: "Removes use of deprecated Class.newInstance()." |
| 24 | +- icon: "🎯" |
| 25 | + title: "Explicit constructor" |
| 26 | + desc: "The requested signature is visible and can accept arguments." |
| 27 | +- icon: "🛡" |
| 28 | + title: "Honest failures" |
| 29 | + desc: "Constructor exceptions are represented through InvocationTargetException." |
| 30 | +support: |
| 31 | + state: "available" |
| 32 | + description: "Recommended since Class.newInstance() was deprecated in JDK 9 (September 2017)." |
| 33 | +prev: "tooling/junit6-with-jspecify" |
| 34 | +next: "language/anonymous-classes-to-lambdas" |
| 35 | +related: |
| 36 | +- "tooling/class-file-api" |
| 37 | +- "io/url-constructors-to-uri" |
| 38 | +- "language/compact-canonical-constructor" |
| 39 | +tags: |
| 40 | +- tooling |
| 41 | +- migration |
| 42 | +- constructors |
| 43 | +- exceptions |
| 44 | +docs: |
| 45 | +- title: "Class.getDeclaredConstructor()" |
| 46 | + href: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Class.html#getDeclaredConstructor(java.lang.Class...)" |
| 47 | +- title: "Constructor.newInstance()" |
| 48 | + href: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/reflect/Constructor.html#newInstance(java.lang.Object...)" |
0 commit comments