Object is the root class of the class hierarchy, so a String can be assigned directly to an Object reference. The actual object remains a String, even though it is referenced through a variable of type Object.
- Assigning a String to an Object reference does not change the String into a different type.
- getClass() can be used to determine the actual runtime type of the object.
- Class.forName() is used to load and obtain metadata about a class from its name; it does not convert a String value into an Object.
Methods To Convert String To Object
1. Using the Assignment Operator
Since String is a subclass of Object, a String can be assigned directly to an Object reference. This is an example of upcasting, where a child-class object is referred to using a parent-class reference.
public class Main {
public static void main(String[] args) {
// Create a String
String str = "GeeksForGeeks";
// Assign String to an Object reference
Object object = str;
// Display the actual class of the object
System.out.println("Class of object: "
+ object.getClass().getName());
// Display the object
System.out.println("Object: " + object);
}
}
Output
Class of object: java.lang.String Object: GeeksForGeeks
Explanation: The String is assigned to an Object reference because String extends Object. The getClass() method confirms that the actual object stored in the reference is still a String.
2. Using Class.forName() Method
The Class.forName() method is used when the name of a class is available as a String and we want to obtain the corresponding Class object.
Syntax
Class.forName(String className);
The method accepts the fully qualified class name as a String and returns a Class object representing that class. If the specified class cannot be found, it throws ClassNotFoundException.
public class Main {
public static void main(String[] args) {
try {
// Class name provided as a String
String className = "java.lang.String";
// Get the Class object
Class<?> classObject = Class.forName(className);
// Display the class name
System.out.println("Class name: "
+ classObject.getName());
// Display the superclass name
System.out.println("Superclass name: "
+ classObject.getSuperclass().getName());
} catch (ClassNotFoundException e) {
System.out.println("Class not found: "
+ e.getMessage());
}
}
}
Output
Class name: java.lang.String Superclass name: java.lang.Object
Explanation: Here, "java.lang.String" is a String containing the name of a class. Class.forName() loads that class and returns a Class object representing String. The getSuperclass() method then shows that String directly extends Object.