How to Convert String to Object in Java

Facebooktwitterredditpinterestlinkedinmailby feather

How to Convert String to Object in Java

The Object is the super class of all classes. So you can assign a string to Object directly. There are two methods to convert String to Object.

  • Using Assignment Operator
  • Using Class.forName() method

Using Assignment Operator

You can convert String to Object by using the assignment operator. An assignment operator assigns the string into the reference variable of the Object class.

Example

In the following example, we have taken a variable str of type String and initialized “book” into it. An Object is a super class of all classes. obj is a reference variable of the class Object that stores the string str as an object. The println statement prints the object that contains a string.

Output

Using Class.forName() method

There is another method Class.forName() to convert String to Object. It belongs to java.lang package. It creates an instance of java.lang.Class and forces the class loader to load this class, and execute code in its static block. The Class.forName() method returns the Class object associated with the class or interfaces with the specified string.

Example

In the following example, getName() is the method of java.lang.reflect.Method class. It returns the method name as a string.

The java.lang.Class class has a method getSuperclass(). It is used to retrieve the direct super class. It returns a Class object representing the super class of the Class Object on which the method is called. If the method is called on the object class, then it returns null.

The first println statement prints the class name and the second println statement prints the super class name of the class java.lang.String.

We should use either try-catch block or write throws Exception just after the main method because it throws ClassNotFoundException.

Output

 

Facebooktwitterredditpinterestlinkedinmailby feather