📜  Java中的 Class forName(String, boolean, ClassLoader) 方法及示例

📅  最后修改于: 2022-05-13 01:54:18.332000             🧑  作者: Mango

Java中的 Class forName(String, boolean, ClassLoader) 方法及示例

Java.lang.Class 类forName(String, boolean, ClassLoader)方法用于获取具有指定类名的这个Class的实例,使用指定的类加载器。仅当 initialize 参数为 true 且之前未初始化时,才会初始化该类。
句法:

public static Class
 forName(String className, 
         boolean initialize, 
         ClassLoader classLoader) 
 throws ClassNotFoundException

参数:此方法接受以下参数:

  • className是需要其实例的类。
  • initialize这是一个布尔值,用于说明是否需要初始化此类实例。
  • classLoader是必须从中加载这个 Class 的 ClassLoader。

返回值:该方法返回使用指定参数获取的此类的实例。
异常:此方法抛出以下异常:

  • LinkageError:如果链接失败
  • ExceptionInInitializerError:如果此方法引发的初始化失败
  • ClassNotFoundException:如果找不到该类
  • SecurityException:如果存在安全管理器,并且加载器为空,并且调用者的类加载器不为空,并且调用者没有 RuntimePermission(“getClassLoader”)

下面的程序演示了 forName() 方法。
示例 1:

Java
// Java program to demonstrate forName() method
 
public class Test {
    public static void main(String[] args)
        throws ClassNotFoundException
    {
 
        // returns the Class object for this class
        Class myClass = Class.forName("Test");
 
        ClassLoader loader = myClass.getClassLoader();
 
        // get the Class instance using forName method
        Class c1
            = Class.forName("java.lang.String",
                            true,
                            loader);
 
        System.out.print("Class represented by c1: "
                         + c1.toString());
    }
}


Java
// Java program to demonstrate forName() method
 
public class Test {
    public static void main(String[] args)
        throws ClassNotFoundException
    {
 
        // returns the Class object for this class
        Class myClass = Class.forName("Test");
 
        ClassLoader loader = myClass.getClassLoader();
 
        // get the Class instance using forName method
        Class c1
            = Class.forName("java.lang.Integer",
                            false,
                            loader);
 
        System.out.print("Class represented by c1: "
                         + c1.toString());
    }
}


输出:
Class represented by c1: class java.lang.String

示例 2:

Java

// Java program to demonstrate forName() method
 
public class Test {
    public static void main(String[] args)
        throws ClassNotFoundException
    {
 
        // returns the Class object for this class
        Class myClass = Class.forName("Test");
 
        ClassLoader loader = myClass.getClassLoader();
 
        // get the Class instance using forName method
        Class c1
            = Class.forName("java.lang.Integer",
                            false,
                            loader);
 
        System.out.print("Class represented by c1: "
                         + c1.toString());
    }
}
输出:
Class represented by c1: class java.lang.Integer

参考: https://docs.oracle.com/javase/9/docs/api/ Java/lang/Class.html#forName-java.lang.String-boolean-java.lang.ClassLoader-