Fix RemappingURLClassLoader zip file closed (#336)

This commit is contained in:
IzzelAliz 2021-08-04 12:55:37 +08:00
parent 2fdfa68fac
commit 1abde6a24a

View File

@ -15,6 +15,7 @@ import java.net.URLConnection;
import java.net.URLStreamHandlerFactory; import java.net.URLStreamHandlerFactory;
import java.security.CodeSource; import java.security.CodeSource;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.jar.Manifest;
public class RemappingURLClassLoader extends URLClassLoader implements RemappingClassLoader { public class RemappingURLClassLoader extends URLClassLoader implements RemappingClassLoader {
@ -40,12 +41,17 @@ public class RemappingURLClassLoader extends URLClassLoader implements Remapping
String path = name.replace('.', '/').concat(".class"); String path = name.replace('.', '/').concat(".class");
URL resource = this.getResource(path); URL resource = this.getResource(path);
if (resource != null) { if (resource != null) {
try {
URLConnection connection; URLConnection connection;
Callable<byte[]> byteSource; Callable<byte[]> byteSource;
Manifest manifest;
try { try {
connection = resource.openConnection(); connection = resource.openConnection();
connection.connect(); connection.connect();
if (connection instanceof JarURLConnection && ((JarURLConnection) connection).getManifest() != null) {
manifest = ((JarURLConnection) connection).getManifest();
} else {
manifest = null;
}
byteSource = () -> { byteSource = () -> {
try (InputStream is = connection.getInputStream()) { try (InputStream is = connection.getInputStream()) {
byte[] classBytes = ByteStreams.toByteArray(is); byte[] classBytes = ByteStreams.toByteArray(is);
@ -63,17 +69,14 @@ public class RemappingURLClassLoader extends URLClassLoader implements Remapping
if (i != -1) { if (i != -1) {
String pkgName = name.substring(0, i); String pkgName = name.substring(0, i);
if (getPackage(pkgName) == null) { if (getPackage(pkgName) == null) {
if (connection instanceof JarURLConnection && ((JarURLConnection) connection).getManifest() != null) { if (manifest != null) {
this.definePackage(pkgName, ((JarURLConnection) connection).getManifest(), ((JarURLConnection) connection).getJarFileURL()); this.definePackage(pkgName, manifest, ((JarURLConnection) connection).getJarFileURL());
} else { } else {
this.definePackage(pkgName, null, null, null, null, null, null, null); this.definePackage(pkgName, null, null, null, null, null, null, null);
} }
} }
} }
result = this.defineClass(name, classBytes._1, 0, classBytes._1.length, classBytes._2); result = this.defineClass(name, classBytes._1, 0, classBytes._1.length, classBytes._2);
} catch (IOException e) {
throw new ClassNotFoundException(name, e);
}
} }
if (result == null) { if (result == null) {
throw new ClassNotFoundException(name); throw new ClassNotFoundException(name);