Home > Java > javaTutorial > How Can I Instantiate Java Classes Using Only Their String Names?

How Can I Instantiate Java Classes Using Only Their String Names?

Mary-Kate Olsen
Release: 2024-12-11 19:08:20
Original
179 people have browsed it

How Can I Instantiate Java Classes Using Only Their String Names?

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();
Copy after login

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:

  1. Retrieve the Class object using Class.forName().
  2. Obtain the constructor object using the getConstructor() method, specifying the parameter types if necessary.
  3. Instantiate the class by invoking newInstance() on the constructor object, passing the required parameters.
Class<?> clazz = Class.forName("com.foo.MyClass");
Constructor<?> constructor = clazz.getConstructor(String.class, Integer.class);
Object instance = constructor.newInstance("stringparam", 42);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template