我有以下代码来检索http和https的默认URLStreamHandlers,这是通过访问静态包作用域方法URL.getURLStreamHandler()在Java8中工作的。
private URLStreamHandler getURLStreamHandler(String protocol) {
try {
Method method = URL.class.getDeclaredMethod("getURLStreamHandler", String.class);
method.setAccessible(true);
return (URLStreamHandler) method.invoke(null, protocol);
} catch (Exception e) {
logger.warning("could not access URL.getUrlStreamHandler");
return null;
}
}在使用拼图的Java9中,这仍然是可能的吗?还是会以这种方式修改可见性呢?
发布于 2016-04-09 13:15:36
在早期的原型中,它曾经是可能的,但现在已经不可能了。Jigsaw的可访问性规则现在只限制对public元素(类型、方法、字段)的访问。
在您的示例中,对method.setAccessible(true)的调用将失败,其中包含一条与此类似的消息:
java.lang.reflect.InaccessibleObjectException:无法使getURLStreamHandler可访问:模块java.不是“打开java.”未命名模块@1941a8ff
有关如何解决这一问题,请参见这个问题。
https://stackoverflow.com/questions/36513247
复制相似问题