Objectis the root class of the class hierarchy, so aStringcan be assigned directly to anObjectreference. The actual object remains aString, even though it is referenced through a variable of typeObject.
- Assigning a String to anObjectreference 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 doesnotconvert a String value into an Object.
Methods To Convert String To Object
1. Using the Assignment Operator
SinceStringis a subclass ofObject, a String can be assigned directly to anObjectreference. This is an example ofupcasting, where a child-class object is referred to using a parent-class reference.
Javapublic 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. UsingClass.forName()Method
TheClass.forName()method is used when the name of a class is available as a String and we want to obtain the correspondingClassobject.
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.
Javapublic 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.