To get the Class
object for a class in Java by its string name, you can use the forName()
method of the Class
class. This method takes a string that specifies the fully qualified name of the class and returns the corresponding Class
object.
Here's an example of how to use the forName()
method to get the Class
object for a class by its string name:
import java.util.Date; public class Main { public static void main(String[] args) throws Exception { String className = "java.util.Date"; Class cls = Class.forName(className); Date date = (Date) cls.newInstance(); System.out.println(date); // prints the current date and time } }Souw:ecrww.lautturi.com
This code uses the forName()
method to get the Class
object for the java.util.Date
class, based on the string name "java.util.Date". The newInstance()
method of the Class
object is then used to create a new instance of the Date
class.
You can use the forName()
method to get the Class
object for any class in the Java Class Library or any class that is available on the classpath.
Please note that the forName()
method throws a ClassNotFoundException
if the specified class is not found, so you will need to handle this exception in your code.