Creating Instances Dynamically in Java
Instantiating classes by name is a frequently encountered scenario in programming. Java provides multiple ways to achieve this.
Method 1: For Classes with No-Arg Constructors
For classes with no-argument (no-arg) constructors, the Class.forName() method can be utilized. It returns a Class object, and the subsequent newInstance() method creates an instance of the specified class.
Class<?> clazz = Class.forName("java.util.Date"); Object date = clazz.newInstance();
Method 2: A More Versatile Approach
This method is preferred when classes may not have no-arg constructors. It involves obtaining the Constructor object and then invoking its newInstance() method.
Class<?> clazz = Class.forName("com.foo.MyClass"); Constructor<?> constructor = clazz.getConstructor(String.class, Integer.class); Object instance = constructor.newInstance("stringparam", 42);
Considerations
Both methods utilize reflection, which can cause exceptions if:
The above is the detailed content of How Can I Create Java Instances Dynamically?. For more information, please follow other related articles on the PHP Chinese website!