如何在Java处理Java .lang.UnsatisfiedLinkError ?
Java.lang.UnsatisfiedLinkError是 LinkageError 类的子类。当Java虚拟机 (JVM) 没有找到声明为“本机”的方法时,它将抛出 UnsatisfiedLinkError。
现在让我们讨论它何时以及为什么发生。 Java.lang.UnsatisfiedLinkError 在程序编译过程中发生。这是因为编译器没有找到 Native Library 的原因,一个包含仅适用于指定操作系统的原生代码的库,Native 库如 Windows 中的.dll ,Linux 中的.so和 Mac 中的.dylib 。此错误的层次结构如下所示:
Java.lang.Object
Java.lang.Throwable
Java.lang.Error
Java.lang.LinkageError
Java.lang.UnsatisfiedLinkError
例子
Java
// Java Program to Illustrate UnsatisfiedLinkError
// Importing input output classes
import java.io.*;
// Main class
public class GFG {
// Loading the External Library
//"libfile" is name of C file
static {
System.loadLibrary("libfile");
}
//Method 1
// To define externally in C file
native void cfun();
// Method 2
// Main driver method
public static void main(String[] args) {
// Creating the object of above class inside main()
GFG g = new GFG();
// Calling over the above method
g.cfun();
}
}
Java
// Java Program to Resolve UnsatisfiedLinkError by
// considering C file where native function is defined
// Importing input output classes
import java.io.*;
// Main class
public class GFG {
// Loading the External Library
// "libfile" is name of C file
static
{
System.load(
"C:/Users/SYSTEM/Desktop/CODES/libfile.dll");
}
// Method 1
// Defined externally in C file
native void cfun();
// Method 2
// Main driver method
public static void main(String[] args)
{
// Creating an object of class inside main()
GFG g = new GFG();
// Calling the above object
g.cfun();
}
}
输出:
如上所示,为了处理此错误,我们需要确保 PATH 应包含 Windows 中给定的“DLL”文件。我们还可以检查Java.library.path是否设置。如果我们在 Windows 中使用命令提示符运行Java文件,我们可以使用Java -Djava.library.path="NAME_OF_THE_DLL_FILE" -jar
例子
Java
// Java Program to Resolve UnsatisfiedLinkError by
// considering C file where native function is defined
// Importing input output classes
import java.io.*;
// Main class
public class GFG {
// Loading the External Library
// "libfile" is name of C file
static
{
System.load(
"C:/Users/SYSTEM/Desktop/CODES/libfile.dll");
}
// Method 1
// Defined externally in C file
native void cfun();
// Method 2
// Main driver method
public static void main(String[] args)
{
// Creating an object of class inside main()
GFG g = new GFG();
// Calling the above object
g.cfun();
}
}
输出:当我们运行上述Java文件时,它将成功编译并显示输出。
Hello from C file
Note:
We will generate the .dll file from this C file by using the command- ‘gcc cfile.c -I C:/Program Files/Java/jdk1.8.0_111/include -I C:/Program Files/Java/jdk1.8.0_111/include/win32 -shared -o cfile.dll‘. Now when we run the above java file it will Compile Successfully and display the Output.