Java类类getClassLoader()方法及示例

2022-08-28 12:53:18 浏览数 (1)

大家好,又见面了,我是你们的朋友全栈君。

类的类getClassLoader()方法 (Class class getClassLoader() method)

  • getClassLoader() method is available in java.lang package. getClassLoader()方法在java.lang包中可用。
  • getClassLoader() method is used to return the ClassLoader that loads the class or interface. getClassLoader()方法用于返回加载类或接口的ClassLoader。
  • getClassLoader() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error. getClassLoader()方法是一个非静态方法,只能通过类对象进行访问,如果尝试使用类名称访问该方法,则会收到错误消息。
  • getClassLoader() method may throw SecurityException at the time of loading class or interface. 在加载类或接口时, getClassLoader()方法可能会引发SecurityExceptionSecurityException: In this exception, its checkPermission() method does not allow access classloader for the class when the security manager exists. SecurityException :在此异常中,当安全管理器存在时,其checkPermission()方法不允许访问该类的类加载器。

Syntax:

句法:

代码语言:javascript复制
    public ClassLoader getClassLoader();

Parameter(s):

参数:

  • It does not accept any parameter. 它不接受任何参数。

Return value:

返回值:

The return type of this method is ClassLoader, it returns the following values based on the given cases,

此方法的返回类型为ClassLoader ,它根据给定的情况返回以下值:

  • It returns class loader that loads the class denoted by this object. 它返回类加载器,该加载器加载此对象表示的类。
  • It returns null in case of bootstrap class loader because we don’t need to implement bootstrap class loader. 如果使用自举类加载器,则返回null ,因为我们无需实现自举类加载器。

Example:

例:

代码语言:javascript复制
// Java program to demonstrate the example 
// of ClassLoader getClassLoader() method of Class 

public class GetClassLoaderOfClass {
   
   
 public static void main(String[] args) throws Exception {
   
   

  // It returns the Class object attached with the given 
  //classname
  Class cl = Class.forName("GetClassLoaderOfClass");

  // By using getClassLoader() is to load the class
  ClassLoader class_load = cl.getClassLoader();

  // If any ClassLoader associate with the Class
  if (class_load != null) {
   
   

   Class load_class = class_load.getClass();
   System.out.print("Associated Loader Class: ");
   System.out.print(load_class.getName());
  }
  // No Loader associated with the class
  else
   System.out.println("No system loader associated with the class");
 }
}

Output

输出量

代码语言:javascript复制
Associated Loader Class: jdk.internal.loader.ClassLoaders$AppClassLoader

翻译自: https://www.includehelp.com/java/class-class-getclassloader-method-with-example.aspx

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/146210.html原文链接:https://javaforall.cn

0 人点赞