Java 运行时 load() 方法



描述

Java 运行时 load(String filename) 方法将指定的文件名加载为动态库。文件名参数必须是完整路径名(例如 Runtime.getRuntime().load())。首先,如果存在安全管理器,则其 checkLink 方法将使用文件名作为其参数被调用。这可能会导致安全异常。这类似于 loadLibrary(String) 方法,但它接受一个通用文件名作为参数,而不仅仅是库名,允许加载任何本地代码文件。System.load(String) 方法是调用此方法的常规且便捷的方式。

声明

以下是 java.lang.Runtime.load() 方法的声明

public void load(String filename)

参数

filename - 要加载的文件。

返回值

此方法不返回值。

异常

  • SecurityException - 如果存在安全管理器并且其 checkLink 方法不允许加载指定动态库

  • UnsatisfiedLinkError - 如果文件不存在

  • NullPointerException - 如果 filename 为 null

示例:加载加密 DLL

以下示例演示了 Java 运行时 load() 方法的用法。在此程序中,使用 load() 方法,我们传递 crypt32.dll 的完整路径以加载它,并打印相应的消息。

package com.tutorialspoint;

public class RuntimeDemo {

   public static void main(String[] args) {

      // print when the program starts
      System.out.println("Program starting...");

      // load a library that is Windows/System32 folder
      System.out.println("Loading Library...");
      Runtime.getRuntime().load("C:/Windows/System32/crypt32.dll");
      System.out.println("Library Loaded.");
   }
}

输出

让我们编译并运行上述程序,这将产生以下结果:

Program starting...
Loading Library...
Library Loaded.

示例:加载 DLL 时出现异常

以下示例演示了 Java 运行时 load() 方法的用法。在此程序中,使用 load() 方法,我们传递一个不存在的 dll 的路径以加载它,并打印相应的异常消息。

package com.tutorialspoint;

public class RuntimeDemo {

   public static void main(String[] args) {

      // print when the program starts
      System.out.println("Program starting...");

      // load a library that is Windows/System32 folder
      System.out.println("Loading Library...");
      Runtime.getRuntime().load("C:/Windows/System32/crypt.dll");
      System.out.println("Library Loaded.");
   }
}

输出

让我们编译并运行上述程序,这将产生以下结果:

Program starting...
Loading Library...
Exception in thread "main" java.lang.UnsatisfiedLinkError: Can't load library: C:\Windows\System32\crypt.dll
	at java.base/java.lang.ClassLoader.loadLibrary(ClassLoader.java:2422)
	at java.base/java.lang.Runtime.load0(Runtime.java:852)
	at java.base/java.lang.Runtime.load(Runtime.java:838)
	at com.tutorialspoint.RuntimeDemo.main(RuntimeDemo.java:12)

示例:加载文件管理 DLL

以下示例演示了 Java 运行时 load() 方法的用法。在此程序中,使用 load() 方法,我们传递 filemgmt.dll 的完整路径以加载它,并打印相应的消息。

package com.tutorialspoint;

public class RuntimeDemo {

   public static void main(String[] args) {

      // print when the program starts
      System.out.println("Program starting...");

      // load a library that is Windows/System32 folder
      System.out.println("Loading Library...");
      Runtime.getRuntime().load("C:/Windows/System32/filemgmt.dll");
      System.out.println("Library Loaded.");
   }
}

输出

让我们编译并运行上述程序,这将产生以下结果:

Program starting...
Loading Library...
Library Loaded.
java_lang_runtime.htm
广告

© . All rights reserved.