📌  相关文章
📜  将字符串转换为对象的Java程序

📅  最后修改于: 2022-05-13 01:54:27.472000             🧑  作者: Mango

将字符串转换为对象的Java程序

内置对象类是所有类的父类,即每个类在内部都是对象类的子类。所以我们可以直接给一个对象赋值一个字符串。

基本上,有两种方法可以将 String 转换为 Object。下面是使用这两种方法将字符串转换为对象。

  1. 使用赋值运算符
  2. 使用 Class.forName() 方法

方法 1:使用赋值运算符

赋值运算符将字符串赋值给对象类的引用变量。

Java
// Java Program to convert string to an object
import java.io.*;
import java.util.*;
   
class GFG {
    public static void main(String[] args)
    {
        // string
        String s = "GeeksForGeeks";
        
        // assigning string to an object
        Object object = s;
        
        // to check the data-typeof the object 
        // to confirm that s has been stored in object
       System.out.println("Datatype of the variable in object is : "
                          +object.getClass().getName());
        
       System.out.println("object is : "+object);
    }
}


Java
// Java program to convert the string to an object
  
class GFG {
    public static void main(String[] args) throws Exception
    {
        // getting the instance of the class passed in
        // forName method as a string
        Class c = Class.forName("java.lang.String");
        
        // getting the name of the class
        System.out.println("class name: " + c.getName());
        
        // getting the name of the super class
        System.out.println("super class name: "
                           + c.getSuperclass().getName());
    }
}


输出
Datatype of the variable in object is : java.lang.String
object is : GeeksForGeeks

方法 2:使用 Class.forName() 方法

我们可以 字符串可以使用 Class.forName()方法。

句法:

public static Class forName(String className) throws ClassNotFoundException

参数:此方法接受参数className ,它是需要其实例的类。

返回值:此方法返回具有指定类名的此类的实例。

  • Class 类属于Java.lang 包。
  • Java.lang.Class 类有一个方法 getSuperclass()。它用于检索当前类的超类。此方法返回一个 Class 对象,该对象表示调用该方法的 Class Object 的超类。如果在 object 类上调用该方法,则它将返回 null,因为 Object 类是类层次结构中的最顶层类,并且不能有任何 Object 类的超类。

Java

// Java program to convert the string to an object
  
class GFG {
    public static void main(String[] args) throws Exception
    {
        // getting the instance of the class passed in
        // forName method as a string
        Class c = Class.forName("java.lang.String");
        
        // getting the name of the class
        System.out.println("class name: " + c.getName());
        
        // getting the name of the super class
        System.out.println("super class name: "
                           + c.getSuperclass().getName());
    }
}
输出
class name: java.lang.String
super class name: java.lang.Object