📜  Java中的类 getClassLoader() 方法和示例

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

Java中的类 getClassLoader() 方法和示例

Java.lang.Class 类getClassLoader()方法用于获取该实体的classLoader。这个实体可以是一个类、一个数组、一个接口等。方法返回这个实体的classLoader。
句法:

public ClassLoader getClassLoader()

参数:此方法不接受任何参数。
返回值:该方法返回实体的ClassLoader
下面的程序演示了 getClassLoader() 方法。
示例 1:

Java
// Java program to demonstrate getClassLoader() method
 
public class Test {
    public static void main(String[] args)
        throws ClassNotFoundException
    {
 
        // returns the Class object for this class
        Class myClass = Class.forName("Test");
 
        System.out.println("Class represented by myClass: "
                           + myClass.toString());
 
        // Get the classLoader of myClass
        // using getClassLoader() method
        System.out.println("ClassLoader of myClass: "
                           + myClass.getClassLoader());
    }
}


Java
// Java program to demonstrate getClassLoader() method
 
public class Test {
 
    class Arr {
    }
 
    public static void main(String[] args)
        throws ClassNotFoundException
    {
        // returns the Class object for Arr
        Class arrClass = Arr.class;
 
        // Get the classLoader of arrClass
        // using getClassLoader() method
        System.out.println("ClassLoader of arrClass: "
                           + arrClass.getClassLoader());
    }
}


输出:
Class represented by myClass: class Test
ClassLoader of myClass: sun.misc.Launcher$AppClassLoader@42a57993

示例 2:

Java

// Java program to demonstrate getClassLoader() method
 
public class Test {
 
    class Arr {
    }
 
    public static void main(String[] args)
        throws ClassNotFoundException
    {
        // returns the Class object for Arr
        Class arrClass = Arr.class;
 
        // Get the classLoader of arrClass
        // using getClassLoader() method
        System.out.println("ClassLoader of arrClass: "
                           + arrClass.getClassLoader());
    }
}
输出:
ClassLoader of arrClass: sun.misc.Launcher$AppClassLoader@42a57993

参考: https://docs.oracle.com/javase/9/docs/api/ Java/lang/Class.html#getClassLoader–