Reflection
Creating Instances
Instantiate classes dynamically using Constructor.newInstance().
Interview: Compares Class.newInstance() (deprecated) with Constructor.newInstance() and details exception handling.
Reflection allows instantiating classes dynamically using the Constructor.newInstance() API. This is the foundation of dynamic object creation in Java.
Core Idea
Constructor.newInstance() allows invoking a constructor dynamically with arguments.
Why It Matters
Allows factory patterns to instantiate classes by name without hardcoding concrete types.
Interview Lens
Tests why Class.newInstance() is deprecated and how Constructor.newInstance() resolves exception propagation.
Instantiation Methods Compared
Class.newInstance()(Deprecated): Bypasses constructor exceptions (propagates checked exceptions without declaration). It can only call the no-arg constructor, throwing an instantiation error if it doesn't exist.Constructor.newInstance()(Preferred): Wraps all constructor exceptions inInvocationTargetException. It can invoke constructors with any parameters, making it highly flexible.
Code Walkthrough
This program demonstrates instantiating an object using its constructor with arguments.
import java.lang.reflect.Constructor;class User { private String name; public User(String name) { this.name = name; } public String getName() { return name; } }
public class InstantiationDemo { public static void main(String[] args) throws Exception { Class clazz = User.class;
// Find constructor accepting String Constructor constructor = clazz.getConstructor(String.class);
// Instantiate dynamically User user = constructor.newInstance("Alice"); System.out.println("User created: " + user.getName()); // Alice } }
Interview-Relevant Information
Q: Why was Class.newInstance() deprecated?
Answer: Class.newInstance() had a flaw where it bypassed compile-time checked exception validation. If a constructor threw a checked exception, Class.newInstance() propagated it as a checked exception without declaring it in its throws signature, violating Java's exception handling model. Constructor.newInstance() correctly wraps all exceptions inside InvocationTargetException.
Quick Checklist
Why is Constructor.newInstance() preferred over Class.newInstance()? What exceptions can it throw? If yes, you understand dynamic instantiation.
Use Cases
Instantiating handler classes dynamically based on database properties.
Populating mock bean dependencies inside test containers.
Common Mistakes
Using Class.newInstance() and running into unexpected type checking bypass errors.
Invoking newInstance() on classes without matching constructors, throwing NoSuchMethodException.