Search code examples
javaclassmemoryloaderencryption

"NegativeArraySizeException" - Custom Class Loader


I had a class loader working although I am now getting an error after adapting it to my new application. I believe it is because I am converting an integer to a long.

private byte[] loadClassData(String name) {
    try {
        JarInputStream jis = new JarInputStream(new ByteArrayInputStream(dec));
        JarEntry entry = null;
        String entryName = null;
        while((entry = jis.getNextJarEntry()) != null)
        {
            entryName = entry.getName();
            if(entryName.equalsIgnoreCase(name))
            {
                try{
                    classBytes = new byte[(int)entry.getSize()];
                    jis.read(classBytes, 0, classBytes.length);
                    return classBytes;
                }catch(Exception ex){
                    ex.printStackTrace();
                    return null;
                }
            }
        }
        return classBytes;
    } catch (IOException e) {
        e.printStackTrace();
        System.out.println(e.getMessage());
    } catch (Exception ex) {
        ex.printStackTrace();
        System.out.println(ex.getMessage());
    }
    return null;
}

Anyways, that is the basics of it. I am getting an error on the " new byte[(int)entry.getSize()];" part.

"java.lang.NegativeArraySizeException"

Thanks.


Solution

  • Yes, because ZipEntry.getSize() can return -1. Even if it didn't return -1, you shouldn't assume that a single call to read will read all the data. You should read in a loop until the input stream returns -1.

    I suggest you use ByteStreams.toByteArray(InputStream) from Guava for this.