Java - 注册自定义 URL 协议处理程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6278299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java - Registering custom URL protocol handlers
提问by Ariod
I tried to register a custom URL handler for a classpath protocol, as described in another thread. Here is the code:
我尝试为类路径协议注册自定义 URL 处理程序,如另一个线程中所述。这是代码:
package com.mycompany;
import org.junit.Test;
import java.net.MalformedURLException;
import java.net.URL;
import com.mycompany.protocol.classpath.Handler;
public class ParserTest {
@Test
public void testParsing() throws MalformedURLException {
System.out.println(System.getProperty("java.protocol.handler.pkgs"));
//URL url = new URL(null, "classpath://com.mycompany/hello-world.xml", new Handler(ClassLoader.getSystemClassLoader()));
URL url = new URL("classpath://com.mycompany/hello-world.xml");
}
}
The test case has the following JVM arguments:
测试用例具有以下 JVM 参数:
-Djava.protocol.handler.pkgs=com.mycompany.protocol
The System.out.println
line properly outputs com.mycompany.protocol
, so the property is being set. However, it looks like it's not being taken into effect, because the above call will throw a java.net.MalformedURLException: unknown protocol: classpath
exception.
该System.out.println
行正确输出com.mycompany.protocol
,因此正在设置该属性。不过貌似没有生效,因为上面的调用会抛出java.net.MalformedURLException: unknown protocol: classpath
异常。
If I provide the handler explicitly as in the commented line, everything is fine. However, I would rather not provide it explicitly - it should be done automatically.
如果我在注释行中明确提供处理程序,一切都很好。但是,我宁愿不明确提供它 - 它应该自动完成。
What am I doing wrong?
我究竟做错了什么?
采纳答案by Ariod
I have found the issue. The original classpath handler classthat I used had a non-default constructor. Of course, because it had only a non-default constructor, the handler couldn't be instantiated. I apologize to everyone who have tried to debug this issue, I failed to see this connection.
我发现了这个问题。我使用的原始类路径处理程序类有一个非默认构造函数。当然,因为它只有一个非默认构造函数,所以无法实例化处理程序。我向所有试图调试这个问题的人道歉,我没有看到这个连接。
回答by Kiran
Probably easiest way to debug such problems is to enumerate the protocol handlers registered.
调试此类问题的最简单方法可能是枚举已注册的协议处理程序。