【问题标题】:Android - dynamically load class into memoryAndroid - 将类动态加载到内存中
【发布时间】:2016-09-05 10:50:56
【问题描述】:

DexClassLoader 很棒,但只能通过从内部/外部存储加载已编译的类作为 dex/jar 文件来工作。

我怎样才能将类直接加载到内存中,而不先向卡中写入任何内容?

我知道 Peter Lawrey 的 Java-Runtime-Compiler(即时编译字符串到类),这将是完美的,但它在 android 中不起作用。

【问题讨论】:

    标签: java android reflection dexclassloader


    【解决方案1】:

    编写 Java 类加载器的一般原则在这里也适用,所以基本上你需要做的是编写一个可以生成 Class 实例的类加载器,例如通过调用 defineClass()。当然,这涉及到创建一个有效的 dex 字节码数组。我还没有这样做,除了非常特殊的场合,我无论如何都不会尝试这样做。如果您走这条路,请记住只使用 Java 5 和 6 中已经存在的类加载器功能。

    【讨论】:

      【解决方案2】:

      正如 Thomas 所说,您可以反射性地调用您想要加载类的 ClassLoader 的受保护的 defineClass() 方法。

      这是一个如何实现的示例:

      public static Class<?> loadClass(byte[] code, ClassLoader loadInto) throws InvocationTargetException
      {
          try {
              Method m = ClassLoader.class.getDeclaredMethod("defineClass", byte[].class, int.class, int.class);
              m.setAccessible(true); // Make sure we can invoke the method
              return (Class<?>) m.invoke(loadInto, code, 0, code.length);
          }
          // An exception should only be thrown if the bytecode is invalid
          // or a class with the same name is already loaded
          catch (NoSuchMethodException e) { throw new RuntimeException(e); }
          catch (IllegalAccessException e){ throw new RuntimeException(e); }
      }
      

      虽然,我感觉您所指的是根据您包含的链接将包含有效 Java 的字符串运行时编译为字节码。虽然我不知道有什么方法可以做到这一点,但我建议你看看这个:https://github.com/linkedin/dexmaker

      【讨论】:

        【解决方案3】:

        你可以通过InMemoryDexClassLoader来做

        【讨论】:

        • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
        • Link only answers 被认为质量很低,can get deleted,请将链接资源中的重要部分放入答案正文中。
        猜你喜欢
        • 1970-01-01
        • 2015-05-11
        • 2012-08-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-19
        • 1970-01-01
        相关资源
        最近更新 更多