UnsatisfiedLinkError java exception when the class with the native method is not in the default package

让人想犯罪 __ 提交于 2020-02-06 08:49:27

问题


I am trying to open a URL with the default Windows browser, in Java. Unfortunately, I cannot use the Desktop class utilities since the code has to be compatible with 1.5.

As a solution, I am calling ShellExecute by using a native method:

public class ShellExec {
   public native int execute(String document);

   {
       System.loadLibrary("HSWShellExec");
   }

   public static void main(String args[]) throws IOException {
       new ShellExec().execute("http://www.google.com/");
   }

}

I put the DLL file in the Eclipse project root which apparently is included in java.library.path .

Everything works just perfect if ShellExec is in the default package, but if I move it in any other package, the native call fails with:

Exception in thread "main" java.lang.UnsatisfiedLinkError: apackage.ShellExec.execute(Ljava/lang/String;)I
at apackage.ShellExec.execute(Native Method)
at apackage.ShellExec.main(ShellExec.java:13)

Anybody has any ideea why? I am using the DLL from http://www.heimetli.ch/shellexec.html

Thanks

..later edit:

Eventually this class, and others, will be utility classes in an Eclipse RCP application, and all the external DLLs will be placed in a common lib folder to which the java.library.path will point to. The DLLs are seen, but I get the same type of errors as the simple example from above.


回答1:


pass the VM argument -Djava.library.path=<path-to-dll-folder> to your project launch configuration.




回答2:


The block you are loading the library in is not static to the class, just defined as an anonymous block in an instance of ShellExec. Since you never create an instance of ShellExec, the anonymous block never gets called and the library never gets loaded.

Instead you should have

static {
   System.loadLibrary("HSWShellExec");
}

I think that will solve your problem.



来源:https://stackoverflow.com/questions/8761979/unsatisfiedlinkerror-java-exception-when-the-class-with-the-native-method-is-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!