[英]How do I load a native library from Java depending on the use-case?
I have a use-case depending on which I want to load libraries. 我有一个用例,具体取决于要加载的库。
if(useCase) {
Static { System.loadLibrary("a") };
}
else {
Static { System.loadLibrary("b") };
}
Till now, I had just one library to load so I was loading it static in the class declaration but now I have this use-case and depending on it I need to load the library. 到现在为止,我只加载了一个库,因此我在类声明中将其静态加载,但现在有了这个用例,并需要根据它来加载库。
I was trying to load the library in the constructor only but any static declaration inside a constructor is not allowed, and I am confused what other ways are there by which I can achieve the same? 我试图只在构造函数中加载库,但不允许在构造函数中进行任何静态声明,而且我很困惑还有其他哪些方法可以实现相同目的?
I want to load the libraries as static only. 我只想将库加载为静态库。 Any help would be appreciated. 任何帮助,将不胜感激。
Please use custom class loader. 请使用自定义类加载器。 below is the link for more info http://tutorials.jenkov.com/java-reflection/dynamic-class-loading-reloading.html 以下是更多信息的链接http://tutorials.jenkov.com/java-reflection/dynamic-class-loading-reloading.html
It is easy to call loadLibrary()
from static {} (class) constructor, because this way you ensure that the code that implements native methods of your class, is available when the classloader needs it to initialize the class, like here: 从静态{} (类)构造函数中调用loadLibrary()
很容易,因为这样可以确保当类加载器需要它来初始化类时,可以使用实现类的本机方法的代码,如下所示:
public class ClassWithNativeMethods {
static {
System.loadLibrary("a");
}
native void method1();
}
class ClassThatUsesClassWithNativeMethods {
ClassWithNativeMethods field = new ClassWithNativeMethods();
}
If your Java has two different scenarios that involve loading different native libraries, you can load this library before loading this class: 如果您的Java有两种涉及加载不同本机库的方案,则可以在加载此类之前加载此库:
public class ClassWithNativeMethods {
native void method1();
}
class ClassThatUsesClassWithNativeMethods {
ClassWithNativeMethods field;
public ClassThatUsesClassWithNativeMethods(bool useCase) {
if (useCase) {
System.loadLibrary("a");
}
else {
System.loadLibrary("b");
}
field = new ClassWithNativeMethods();
}
}
If the condition is static , you can use it inside static constructor: 如果条件是static ,则可以在static构造函数中使用它:
public class ClassWithNativeMethods {
static {
if (BuildConfig.useCase) {
System.loadLibrary("a");
else {
System.loadLibrary("b");
}
}
native void method1();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.