Java Class forName(String className) 方法



描述

Java Class forName(String className) 方法返回與給定字串名稱的類或介面關聯的 Class 物件。

宣告

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

public static Class<?> forName(String className) throws ClassNotFoundException

引數

className − 這是所需類的完全限定名稱。

返回值

此方法返回具有指定名稱的類的 Class 物件。

異常

  • LinkageError − 如果連結失敗。

  • ExceptionInInitializerError − 如果此方法觸發的初始化失敗。

  • ClassNotFoundException − 如果找不到該類。

按名稱獲取類示例

以下示例演示了 java.lang.Class.forName() 方法的使用。使用 forName() 方法,我們透過其名稱獲得了 ClassLoader 類的 Class。然後使用 getName 列印類的名稱,使用 getPackage() 列印類的包名稱。

package com.tutorialspoint;

public class ClassDemo {

   public static void main(String[] args) {

      try {
         // returns the Class object for the class with the specified name
         Class cls = Class.forName("java.lang.ClassLoader");
         
         // returns the name and package of the class
         System.out.println("Class found = " + cls.getName());
         System.out.println("Package = " + cls.getPackage());
      } catch(ClassNotFoundException ex) {
         System.out.println(ex.toString());
      }
   }
}

輸出

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

Class found = java.lang.ClassLoader
Package = package java.lang, Java Platform API Specification, version 1.8

按名稱獲取自定義類示例

以下示例演示了 java.lang.Class.forName() 方法的使用。使用 forName() 方法,我們透過其完全限定名稱獲得了 ClassDemo 類的 Class。然後使用 getName 列印類的名稱,使用 getPackage() 列印類的包名稱。

package com.tutorialspoint;

public class ClassDemo {

   public static void main(String[] args) {

      try {
         // returns the Class object for the class with the specified name
         Class cls = Class.forName("com.tutorialspoint.ClassDemo");
         
         // returns the name and package of the class
         System.out.println("Class found = " + cls.getName());
         System.out.println("Package = " + cls.getPackage());
      } catch(ClassNotFoundException ex) {
         System.out.println(ex.toString());
      }
   }
}

輸出

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

Class found = com.tutorialspoint.ClassDemo
Package = package com.tutorialspoint

獲取自定義類時遇到異常示例

以下示例演示了 java.lang.Class.forName() 方法的使用。使用 forName() 方法,我們透過其名稱獲得了 ClassDemo 類的 Class。然後使用 getName 列印類的名稱,使用 getPackage() 列印類的包名稱。

package com.tutorialspoint;

public class ClassDemo {

   public static void main(String[] args) {

      try {
         // returns the Class object for the class with the specified name
         Class cls = Class.forName("ClassDemo");
         
         // returns the name and package of the class
         System.out.println("Class found = " + cls.getName());
         System.out.println("Package = " + cls.getPackage());
      } catch(ClassNotFoundException ex) {
         System.out.println(ex.toString());
      }
   }
}

輸出

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

java.lang.ClassNotFoundException: ClassDemo
java_lang_class.htm
廣告
© . All rights reserved.