重写查找资源

overriding findResource

我有一个自定义类加载器,我希望 getResource 在自定义位置查找资源。
因此,我想要做的是覆盖 findResource,因为我希望它成为 return 一个字节数组作为结果。
findResource函数的return类型是URL.
所以问题是,如何从 byte[] 创建一个 URL 对象?

我试过这个方法好像无效:

public class MyClassLoader extends ClassLoader
{
    byte[] myByteArray = new byte[] {0x1, 0x2, 0x3};
    protected URL findResource(String name)
    {
        URL res = super.findResource(name);
        res = new URL(new String(myByteArray));
        return res;
    }
}

当我尝试 运行 时,我遇到了异常:

MalformedURLException: no protocol ?PNG ......

我知道它认为协议是“?PNG ...”(以及后面的内容),但是 byte[] 的正确协议是什么?

过去,我在构造过程中将自定义 URLStreamHandler 附加到 URL。例如:

public class MyClassLoader extends ClassLoader
{
    final byte[] myByteArray = new byte[] {0x1, 0x2, 0x3};
    protected URL findResource(String name)
    {
        URL res = super.findResource(name);
        if (res != null) {
            res = new URL(null, "my-bytes:" + name, new URLStreamHandler() {
                protected URLConnection openConnection(URL u) {
                    return new URLConnection() {
                        public void connect() {}

                        public InputStream getInputStream() {
                            return new ByteArrayInputStream(myByteArray);
                        }
                    };
                }
            });
        }
        return res;
    }
}

这相当粗糙(如果启用了 Java 2 安全性,则需要权限),因此您可能需要更完整的 URLStreamHandler 实现,或者您可能需要将其全局注册到 JVM根据尝试使用 URL 的代码的需要(例如,如果调用者希望能够序列化 URLs,通过复制创建新的 URLs,获取长度数据等),但像这样非常基本的东西对于原型设计、调试或作为更完整实施的起点很有用。