关于自定义URLStreamHandler的一次踩坑

关于自定义URLStreamHandler的一次踩坑

  • 20180625 lambo init

说明

通常自定义实现url的协议解析.方案为实现URLStreamHandler.实现其 openConnection 就能够了, 若是咱们执行 new URL("xx://aa/ff").hashCode();ide

public synchronized int hashCode() {
        if (hashCode != -1)
            return hashCode;
		// 实现为转发给自实现的URLStreamHandler 进行处理
        hashCode = handler.hashCode(this);
        return hashCode;
    }

默认URLStreamHandler 处理hashCode为this

protected int hashCode(URL u) {
        int h = 0;

        // Generate the protocol part.
        String protocol = u.getProtocol();
        if (protocol != null)
            h += protocol.hashCode();

        // Generate the host part.
        InetAddress addr = getHostAddress(u);
        if (addr != null) {
            h += addr.hashCode();
        } else {
            String host = u.getHost();
            if (host != null)
                h += host.toLowerCase().hashCode();
        }

        // Generate the file part.
        String file = u.getFile();
        if (file != null)
            h += file.hashCode();

        // Generate the port part.
        if (u.getPort() == -1)
            h += getDefaultPort();
        else
            h += u.getPort();

        // Generate the ref part.
        String ref = u.getRef();
        if (ref != null)
            h += ref.hashCode();

        return h;
    }

其会进行一次url的访问拿到内容参数 hashCode. 但通常咱们定义一个url是内容不会变化的. 咱们自定义协议可使用 如下代码url

@Override
    protected int hashCode(URL u) {
        if(null == u) {
            return 0;
        }
        return u.toString().hashCode();
    }
相关文章
相关标签/搜索