Instantiating Classes by Name in Java
Java provides two methods to instantiate classes by passing their string name:
1. Using Reflection with a No-Arg Constructor
If the target class has a no-argument constructor, you can use the Class.forName() method to obtain the Class object. Subsequently, call the newInstance() method to create an instance:
Class<?> clazz = Class.forName("java.util.Date"); Object date = clazz.newInstance();
2. Using Reflection for Classes with or without No-Arg Constructors
For a more comprehensive approach that works for classes with or without no-arg constructors, follow these steps:
Class<?> clazz = Class.forName("com.foo.MyClass"); Constructor<?> constructor = clazz.getConstructor(String.class, Integer.class); Object instance = constructor.newInstance("stringparam", 42);
Note: Both approaches involve reflection, which should be used judiciously as it can circumvent Java's exception handling and security constraints.
The above is the detailed content of How Can I Instantiate Java Classes Using Only Their String Names?. For more information, please follow other related articles on the PHP Chinese website!