Is it possible to access package scoped methods by reflection in Java 9 with Jigsaw?

谁说我不能喝 提交于 2020-08-04 23:19:32

问题


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

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


回答1:


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.

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

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.



来源:https://stackoverflow.com/questions/36513247/is-it-possible-to-access-package-scoped-methods-by-reflection-in-java-9-with-jig

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!