Search code examples
javaruntimeclassloader

Loading classes at runtime from JAR file bytes


I have byte array of a JAR file and I need to load all the JAR classes at runtime from these bytes.
How can I do this without converting JAR bytes to a file?


Solution

  • You have to wrap that array of bytes into a java.util.ByteArrayInputStream and that in turn into a java.util.jar.JarInputStream.

    The latter has methods to get one entry (most probably a class file, but also possible are some kinds of resources) after the other as an instance of JarEntry, and to read the bytes for each of that.

    final var classes = new ArrayList<byte[]>();
    try( final var inputStream = new JarInputStream( new ByteArrayInputStream( bytes ) ) )
    {
      var entry = inputStream.getNextJarEntry();
      while( nonNull( entry ) )
      {
        var buffer = new bytes [entry.getSize()];
        inputStream.read( buffer, 0, entry.getSize() );
        classes.add( buffer );
        entry = inputStream.getNextJarEntry();
      }
    }
    

    Ok, this is not tested, and of course there is none of the required error handling, and perhaps you would prefer to store the class data in a map, with the class name as the key …

    Have fun!