Java 類 toString() 方法



描述

Java 類 toString() 方法將物件轉換為字串。字串表示形式是字串“class”或“interface”,後面跟著一個空格,然後是類的完全限定名稱,格式由getName返回。

宣告

以下是java.lang.Class.toString()方法的宣告

public String toString()

引數

返回值

此方法返回此類物件的字串表示形式。

異常

獲取類例項的字串表示形式示例

以下示例顯示了 java.lang.Class.toString() 方法的用法。我們建立了一個 ClassDemo 類的例項,然後使用 getClass() 方法檢索了物件的類。現在使用 toString(),我們獲取字串表示形式並列印結果。我們還使用 getName() 方法列印了類名。

package com.tutorialspoint;

public class ClassDemo {

   public static void main(String[] args) {

      ClassDemo c = new ClassDemo();
      Class cls = c.getClass();

      // returns the string representation of this class object
      String str = cls.toString();
      System.out.println("Class = " + str);

      // returns the name of the class
      str = cls.getName();
      System.out.println("Class = " + str);
   }
} 

輸出

讓我們編譯並執行以上程式,這將產生以下結果:

Class = class com.tutorialspoint.ClassDemo
Class = com.tutorialspoint.ClassDemo

獲取 ArrayList 的字串表示形式示例

以下示例顯示了 java.lang.Class.toString() 方法的用法。我們使用了 ArrayList 的類。現在使用 toString(),我們獲取字串表示形式並列印結果。我們還使用 getName() 方法列印了類名。

package com.tutorialspoint;

import java.util.ArrayList;

public class ClassDemo {

   public static void main(String[] args) {
      Class cls = ArrayList.class;

      // returns the string representation of this class object
      String str = cls.toString();
      System.out.println("Class = " + str);

      // returns the name of the class
      str = cls.getName();
      System.out.println("Class = " + str);
   }
} 

輸出

讓我們編譯並執行以上程式,這將產生以下結果:

Class = class java.util.ArrayList
Class = java.util.ArrayList

獲取 Thread 的字串表示形式示例

以下示例顯示了 java.lang.Class.toString() 方法的用法。我們使用了 Thread 的類。現在使用 toString(),我們獲取字串表示形式並列印結果。我們還使用 getName() 方法列印了類名。

package com.tutorialspoint;

public class ClassDemo {

   public static void main(String[] args) {
      Class cls = Thread.class;

      // returns the string representation of this class object
      String str = cls.toString();
      System.out.println("Class = " + str);

      // returns the name of the class
      str = cls.getName();
      System.out.println("Class = " + str);
   }
} 

輸出

讓我們編譯並執行以上程式,這將產生以下結果:

Class = class java.lang.Thread
Class = java.lang.Thread
java_lang_class.htm
廣告