Java 類 getSimpleName() 方法



描述

Java 類 getSimpleName() 方法返回底層類的簡單名稱,如原始碼中所示。如果底層類是匿名類,則返回空字串。

宣告

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

public String getSimpleName()

引數

返回值

此方法返回底層類的簡單名稱。

異常

獲取類的簡單名稱示例

以下示例演示了 java.lang.Class.getSimpleName() 方法的使用。在此程式中,我們建立了一個 ClassDemo 的例項,然後使用 getClass() 方法檢索例項的類。使用 getSimpleName(),我們檢索了類的簡單名稱,然後列印了它的名稱。

package com.tutorialspoint;

public class ClassDemo {

   public static void main(String[] args) {

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

      // returns the name of the class
      String name = cls.getName();
      System.out.println("Class Name = " + name);
     
      // returns the simple name of the class
      String sname = cls.getSimpleName();
      System.out.println("Class SimpleName = " + sname);     
   }
} 

輸出

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

Class Name = com.tutorialspoint.ClassDemo
Class SimpleName = ClassDemo

獲取 ArrayList 的簡單名稱示例

以下示例演示了 java.lang.Class.getSimpleName() 方法的使用。在此程式中,我們使用了 ArrayList 的類。使用 getSimpleName(),我們檢索了類的簡單名稱,然後列印了它的名稱。

package com.tutorialspoint;

import java.util.ArrayList;

public class ClassDemo {

   public static void main(String[] args) {

      Class cls = ArrayList.class;

      // returns the name of the class
      String name = cls.getName();
      System.out.println("Class Name = " + name);
     
      // returns the simple name of the class
      String sname = cls.getSimpleName();
      System.out.println("Class SimpleName = " + sname);     
   }
} 

輸出

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

Class Name = java.util.ArrayList
Class SimpleName = ArrayList

獲取 ArrayList 的簡單名稱示例

以下示例演示了 java.lang.Class.getSimpleName() 方法的使用。在此程式中,我們使用了 ArrayList 的類。使用 getSimpleName(),我們檢索了類的簡單名稱,然後列印了它的名稱。

package com.tutorialspoint;

import java.util.ArrayList;

public class ClassDemo {

   public static void main(String[] args) {

      Class cls = ArrayList.class;

      // returns the name of the class
      String name = cls.getName();
      System.out.println("Class Name = " + name);
     
      // returns the simple name of the class
      String sname = cls.getSimpleName();
      System.out.println("Class SimpleName = " + sname);     
   }
} 

輸出

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

Class Name = java.util.ArrayList
Class SimpleName = ArrayList

獲取 Thread 的簡單名稱示例

以下示例演示了 java.lang.Class.getSimpleName() 方法的使用。在此程式中,我們使用了 Thread 的類。使用 getSimpleName(),我們檢索了類的簡單名稱,然後列印了它的名稱。

package com.tutorialspoint;

public class ClassDemo {

   public static void main(String[] args) {

      Class cls = Thread.class;

      // returns the name of the class
      String name = cls.getName();
      System.out.println("Class Name = " + name);
     
      // returns the simple name of the class
      String sname = cls.getSimpleName();
      System.out.println("Class SimpleName = " + sname);     
   }
} 

輸出

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

Class Name = java.lang.Thread
Class SimpleName = Thread
java_lang_class.htm
廣告

© . All rights reserved.