Skip to content

[Pattern] Class.newInstance() to constructor reflection #205

Description

@brunoborges

Category

tooling

Slug

class-newinstance-to-constructor

Title

Class.newInstance() to constructor reflection

Difficulty

intermediate

Since JDK

9

Summary

Replace deprecated Class.newInstance() with explicit constructor lookup and invocation.

Old code label

Deprecated Class.newInstance()

Old code

Plugin plugin = pluginClass.newInstance();

Modern code label

Constructor reflection

Modern code

Plugin plugin = pluginClass
        .getDeclaredConstructor()
        .newInstance();

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.

Why the modern way wins

✅ Supported API — Removes use of deprecated Class.newInstance().
🎯 Explicit constructor — The requested signature is visible and can accept arguments.
🛡 Honest failures — Constructor exceptions are represented through InvocationTargetException.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

slugNew or updated pattern snippet (category/slug.json)

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions