java - 重写 findResource

标签 java resources arrays classloader

我有一个自定义类加载器,我希望 getResource 在自定义位置查找资源。
因此,我想做的是重写 findResource,因为我希望它返回一个字节数组作为结果。
findResource函数的返回类型是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 ......

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

最佳答案

过去,我在构造过程中将自定义 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(例如,如果调用者希望能够序列化 URL、通过复制创建新的 URL、获取数据的长度等),但是像这样的非常基本的东西对于原型(prototype)设计、调试或作为起始非常有用更完整的实现点。

关于java - 重写 findResource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30151837/

相关文章:

javascript - 如何从 JavaScript 数组中删除项目?

java - 为什么依赖注入(inject)需要另一种语言?

java - 使用 Java 客户端库的 Google Subscription Defer 会出现 500 Internal Server Error

java - 如何关闭扫描仪?

java - webview 选择文件 android 不工作

android - 加载由 android.R.attr.* 表示的资源

json - 在 Grails 2.3.x 的域类上更改 @Resource 结果的 max 属性的默认值

arrays - Swift:将文本字段保存在数组中

hadoop - Hadoop 资源管理器将应用程序信息存储多长时间?

ios - Swift 将不同类型组合成一个数组来为 UITableView 显示数据