import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public class JarClassLoader extends ClassLoader {
private String path;
public JarClassLoader(String path) {
this.path = path;
}
@Override
public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException
{
Class<?> c = findLoadedClass(name);
if (c == null) {
try {
c = findSystemClass(name);
} catch (Exception e) {
}
if (c != null)
return c;
try {
byte data[] = loadClassData(name);
c = defineClass(name, data, 0, data.length);
if (c == null)
throw new ClassNotFoundException(name);
if (resolve)
resolveClass(c);
} catch (Exception e) {
e.printStackTrace();
}
}
return c;
}
private byte[] loadClassData (String classEntry) throws IOException {
System.out.println(classEntry);
String filename = classEntry.replace('.', File.separatorChar) + ".class";
JarFile jar = new JarFile(path);
JarEntry entry = jar.getJarEntry(filename);
InputStream is = jar.getInputStream(entry);
int data;
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
while ((data = is.read()) != -1) {
byteStream.write(data);
}
return byteStream.toByteArray();
}
}
我有一个ClassLoader(上面发布)从jar中加载我需要的所有类文件。它还包含MySQL java驱动程序文件,当它尝试加载那些时,我在com.mysql.jdbc.LocalizedErrorMessages上收到错误,因为这是一个ResourceBundle。我的问题是如何使用自定义类加载器加载资源包?谢谢你的帮助。
答案 0 :(得分:4)
您需要覆盖并实现findResource()/ findResources()方法。加载资源包属性文件和其他非类文件时使用这些方法。