简体   繁体   English

从jar加载类

[英]Class loading class from jar

This is the common approach with working with loading class dynamically: 这是动态处理类的常用方法:

try {
        File file = new File(JAR_FILE);
        String classToLoad = "com.mycompany.MyClass";
        URL jarUrl = new URL("jar", "","file:" + file.getAbsolutePath()+"!/");
        URLClassLoader loader = new URLClassLoader(new URL[] {jarUrl}, Thread.currentThread().getContextClassLoader());
        Class c = loader.loadClass(classToLoad); 
    } catch (Exception e) {
        e.printStackTrace();
    }

However, I need an approach where: 但是,我需要一种方法:

  • We don't need to create a File (as the jar I am trying to process is a byte array[] when fetched) 我们不需要创建一个文件(因为我要处理的罐子在提取时是一个字节数组[])
  • Or we won't need to create a temporary file from byte[] array (as AppEngine, the platform I work with does not allow to create temporary files) 否则我们不需要从byte []数组创建临时文件(因为AppEngine,我使用的平台不允许创建临时文件)

You will have to create your own class loader. 您将必须创建自己的类加载器。

Something like this, basic idea in pseudo code: 伪代码的基本思想是这样的:

 class MyClassLoader extends ClassLoader {
     public Class findClass(String name) {
         byte[] b = loadClassData(name);
         return defineClass(name, b, 0, b.length);
     }

     private byte[] loadClassData(String name) {
         JarInputStream jis = new JarInputStream(new ByteArrayInputStream(bytearrayJarData));
         JarEntry entry = jis.getNextJarEntry();
         while (entry != null) {
                //compare entry to requested class
                // if match, return Byte data
                // else entry = jis.getNextJarEntry();
         }
         return null; // nothing found
     }
 }

Write your own ClassLoader and override findClass() . 编写自己的ClassLoader并覆盖findClass() There you can use defineClass() to load your byte[] . 在那里,您可以使用defineClass()来加载byte[]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM