是否可以通过Jigsaw在Java 9中通过反射访问包范围的方法? [英] Is it possible to access package scoped methods by reflection in Java 9 with Jigsaw?

查看:109
本文介绍了是否可以通过Jigsaw在Java 9中通过反射访问包范围的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码通过访问静态包作用域方法URL.getURLStreamHandler()来检索http和https的默认URLStreamHandlers,它们在Java 8中有效:

I have the following code to retrieve the default URLStreamHandlers for http and https which works in Java 8 by accessing the static package scoped method URL.getURLStreamHandler():

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;
    }
}

在Java 9中使用 jigsaw 还是可能的,或者将在这样禁止吗?

Will this still be possible in Java 9 with jigsaw or will modifying the visibility in this way be prohibited?

推荐答案

在早期的原型中它曾经是可能的,但现在已经不存在了.拼图的可访问性规则现在仅限制对public元素(类型,方法,字段)的访问.

It used to be possible in an early prototype but it is no longer. Jigsaw's accessibility rules now restrict access to public elements (types, methods, fields) only.

在您的示例中,对method.setAccessible(true)的调用将失败,并显示类似于以下内容的消息:

In your example the call to method.setAccessible(true) will fail with a message similar to this one:

java.lang.reflect.InaccessibleObjectException:无法使getURLStreamHandler可访问:模块java ....不会打开Java ...."到未命名的模块@ 1941a8ff

java.lang.reflect.InaccessibleObjectException: Unable to make getURLStreamHandler accessible: module java.... does not "opens java...." to unnamed module @1941a8ff

有关此问题的解决方法,请参见此问题.

See this question for how to work around that.

这篇关于是否可以通过Jigsaw在Java 9中通过反射访问包范围的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆