'How to load all classes from the byte array of a JAR file at runtime?
I have an array of bytes of a JAR file and I need to load all the classes from this array.
How can I do this without converting this array to a file?
Solution 1:[1]
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!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
