【问题标题】:How do I load a native library from Java depending on the use-case?如何根据用例从 Java 加载本机库?
【发布时间】:2018-02-12 09:12:45
【问题描述】:

我有一个用例,具体取决于我要加载的库。

if(useCase) {
  Static { System.loadLibrary("a") };
}
else {
  Static { System.loadLibrary("b") }; 
}

到目前为止,我只有一个要加载的库,所以我在类声明中静态加载它,但现在我有了这个用例,我需要根据它加载库。

我试图仅在构造函数中加载库,但不允许在构造函数中进行任何静态声明,我很困惑还有哪些其他方法可以实现相同的目标?

我只想将库加载为静态。任何帮助将不胜感激。

【问题讨论】:

  • 为什么要尝试将静态块放在if 语句中,而不是将if 语句放在静态块中?

标签: java java-native-interface native loadlibrary


【解决方案1】:

请使用自定义类加载器。以下是更多信息的链接 http://tutorials.jenkov.com/java-reflection/dynamic-class-loading-reloading.html

【讨论】:

    【解决方案2】:

    静态{}(类)构造函数调用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,你可以在静态构造函数中使用它:

    public class ClassWithNativeMethods {
        static {
            if (BuildConfig.useCase) {
                System.loadLibrary("a");
            else {
                System.loadLibrary("b");
            }
        }
        native void method1();
    }
    

    【讨论】:

    • 我是本地库加载的新手,你能告诉我什么是 BuildConfig 以及我需要更改哪些内容才能在 BuildConfig 中进行静态加载吗?
    • 上面的 BuildConfig 只是一个例子。默认情况下,Android Studio 会为您准备带有 static final 数据的此类,但这可以是任何具有静态 useCase 布尔字段的类,它甚至不需要是 final
    猜你喜欢
    • 2012-07-31
    • 1970-01-01
    • 2018-07-12
    • 2014-07-05
    • 1970-01-01
    • 2018-02-24
    • 1970-01-01
    • 2018-08-08
    • 1970-01-01
    相关资源
    最近更新 更多