问题
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