使用本机API的替代解决方案:JVM_LoadClass0,JVM_AllocateNewArray和JVM_AllocateNewObject

ist*_*tik 7 c c++ java jvm java-9

与Java 9中一样,一些原生API被删除以供弃用,我没有设法找到替代它们的替代解决方案.我是一名C++开发人员,在java方面经验不足.我现在用的是原生API是:JVM_LoadClass0,JVM_AllocateNewObjectJVM_AllocateNewArray.

我在Java中的源代码是:

protected Class resolveClass(MercObjectStreamClass v) throws IOException, ClassNotFoundException
{
    /* Resolve by looking up the stack for a non-zero class
     * loader. If not found use the system loader.
     */
    String name = v.getName();
    try
    {
        //we are using the loadClass0 method which calls the native JVM_LoadClass0
        //JVM_LoadClass0 is deprecated and we need to replace the call
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
      if(loader == null) {
          return loadClass0(null,name);
        }

      Class scriptCls =  loader.loadClass(scriptClassname);
        return loadClass0(scriptCls,name);
    }
    catch (ClassNotFoundException ex)
    {
        Class cl = (Class)primClasses.get(name);
        if (cl != null)
            return cl;
        else
            throw ex;
    }
}
private native Class loadClass0(Class cl, String classname) throws ClassNotFoundException;
Run Code Online (Sandbox Code Playgroud)

然后本机代码只是对JVM_LoadClass0的简单调用:

JNIEXPORT jclass JNICALL
Java_mercio_MercObjectInputStream_loadClass0(JNIEnv * env,
    jobject this,
    jclass curClass,
    jstring currClassName)
{
    return JVM_LoadClass0(env, this, curClass, currClassName);
}
Run Code Online (Sandbox Code Playgroud)

本机部分与其他API类似.

有人可以建议替代这种方法吗?

Mat*_*jek 3

oracle.com 上的此文档页面包含 Java 9 中可用的 JNI 函数的完整列表。

通过查看您提到的旧 JNI 函数,我猜您可能对以下内容特别感兴趣: