Loading resource bundles using a custom class loader

霸气de小男生 提交于 2019-12-01 06:27:05

问题


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();

}

}

I have a ClassLoader (posted above) to load all the class files I need out of a jar. That also contains the MySQL java driver files, and when it's trying to load those I get an error on com.mysql.jdbc.LocalizedErrorMessages because this is a ResourceBundle. My question is how to I load resource bundles using a custom class loader? Thanks for your help.


回答1:


You'll need to override and implement findResource()/findResources() methods. These methods are used when loading resource bundle property files and other non-class files.



来源:https://stackoverflow.com/questions/7923164/loading-resource-bundles-using-a-custom-class-loader

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!