Java, Class Type, String, Class.forName(), Objects
Getting Class Type From a String in Java
In Java, it is sometimes necessary to know the class type of an object from a string representation. This can be done through the use of the Class.forName()
method. This method takes a fully qualified name of a class as the argument and returns a Class
object that represents that class.
The fully qualified name of a class includes both its package name and its class name. For example, if the class MyClass
is located in the package com.example
, then its fully qualified name would be com.example.MyClass
. With this information, it is then possible to get the Class
object for this class using the Class.forName()
method.
Here is an example of how to use the Class.forName()
method to get the Class
object for a given fully qualified class name:
String className = "com.example.MyClass";
Class<?> clazz = Class.forName(className);
System.out.println("Class Type = " + clazz.getName());
// output: Class Type = com.example.MyClass
Once you have the Class
object, you can then check its type with the instanceof
operator or query its methods, fields, and annotations. It is also possible to create new instances of the class by calling the newInstance()
method on the Class
object.
In summary, the Class.forName()
method is a useful utility for getting the Class
type from a fully qualified class name string.