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.