Java Class forName() 方法



描述

Java Class forName(String name, boolean initialize, ClassLoader loader) 方法使用給定的類載入器返回與具有給定字串名稱的類或介面關聯的 Class 物件。

指定的類載入器用於載入類或介面。如果引數loader為 null,則類透過引導類載入器載入。僅當initialize引數為 true 且之前未初始化該類時,才會初始化該類。

宣告

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

public static Class<?> forName(String name, boolean initialize, ClassLoader loader)
   throws ClassNotFoundException

引數

  • name - 這是所需類的完全限定名稱。

  • initialize - 這表示是否必須初始化類。

  • loader - 這是必須從中載入類的類載入器。

返回值

此方法返回表示所需類的類物件。

異常

  • LinkageError - 如果連結失敗。

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

  • ClassNotFoundException - 如果指定的類載入器找不到該類。

透過名稱和給定類載入器獲取類示例

以下示例顯示了 java.lang.Class.forName() 方法的使用。使用 forName() 方法,我們透過其名稱獲得了 ClassDemo 類的 Class。然後使用 getClassLoader 獲取類載入器。使用 classLoader,獲取 Thread 的 Class 並打印出來。

package com.tutorialspoint;

public class ClassDemo {

   public static void main(String[] args) {

      try {
         Class cls = Class.forName("com.tutorialspoint.ClassDemo");

         // returns the ClassLoader object
         ClassLoader cLoader = cls.getClassLoader();
       
         /* returns the Class object associated with the class or interface 
            with the given string name, using the given classloader. */
         Class cls2 = Class.forName("java.lang.Thread", true, cLoader);       
          
         // returns the name of the class
         System.out.println("Class = " + cls.getName());
         System.out.println("Class = " + cls2.getName()); 
      } catch(ClassNotFoundException ex) {
         System.out.println(ex.toString());
      }
   }
}

輸出

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

Class = com.tutorialspoint.ClassDemo
Class = java.lang.Thread

透過名稱和執行緒類載入器獲取類示例

以下示例顯示了 java.lang.Class.forName() 方法的使用。使用 forName() 方法,我們透過其名稱獲得了 ClassDemo 類的 Class。然後使用 Thread.class.getClassLoader() 獲取類載入器。使用 classLoader,獲取 Thread 的 Class 並打印出來。

package com.tutorialspoint;

public class ClassDemo {

   public static void main(String[] args) {

      try {
         Class cls = Class.forName("com.tutorialspoint.ClassDemo");

         /* returns the Class object associated with the class or interface 
            with the given string name, using the given classloader. */
         Class cls2 = Class.forName("java.lang.Thread", true, Thread.class.getClassLoader());       
          
         // returns the name of the class
         System.out.println("Class = " + cls.getName());
         System.out.println("Class = " + cls2.getName()); 
      } catch(ClassNotFoundException ex) {
         System.out.println(ex.toString());
      }
   }
}

輸出

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

Class = com.tutorialspoint.ClassDemo
Class = java.lang.Thread
java_lang_class.htm
廣告

© . All rights reserved.