[英]How do I load a native library from Java depending on the use-case?
我有一个用例,具体取决于要加载的库。
if(useCase) {
Static { System.loadLibrary("a") };
}
else {
Static { System.loadLibrary("b") };
}
到现在为止,我只加载了一个库,因此我在类声明中将其静态加载,但现在有了这个用例,并需要根据它来加载库。
我试图只在构造函数中加载库,但不允许在构造函数中进行任何静态声明,而且我很困惑还有其他哪些方法可以实现相同目的?
我只想将库加载为静态库。 任何帮助,将不胜感激。
请使用自定义类加载器。 以下是更多信息的链接http://tutorials.jenkov.com/java-reflection/dynamic-class-loading-reloading.html
从静态{} (类)构造函数中调用loadLibrary()
很容易,因为这样可以确保当类加载器需要它来初始化类时,可以使用实现类的本机方法的代码,如下所示:
public class ClassWithNativeMethods {
static {
System.loadLibrary("a");
}
native void method1();
}
class ClassThatUsesClassWithNativeMethods {
ClassWithNativeMethods field = new ClassWithNativeMethods();
}
如果您的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();
}
}
如果条件是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.