使用自定义类加载器加载资源包 [英] Loading resource bundles using a custom class loader

查看:783
本文介绍了使用自定义类加载器加载资源包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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。我的问题是如何使用自定义类加载器加载资源包?感谢您的帮助。

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.

推荐答案

您需要覆盖并实现findResource()/ findResources()方法。加载资源包属性文件和其他非类文件时使用这些方法。

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.

这篇关于使用自定义类加载器加载资源包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆