Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

java - How can I make reflection work on JDK 16 and later?

I have the following legacy code that I migrated to Java 16 but, due to the strong encapsulation introduced by this new version, it doesn't work:

try {
    Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
    method.setAccessible(true);
    method.invoke(new URLClassLoader(
        new URL[] {}),
        new File("C:/external-folder/my.jar").toURI().toURL()
    );
} catch (Exception exc) {
    exc.printStackTrace();
}

Is there a way to make it work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is not that reflection "doesn't work"; it is that reflection is finally enforcing more of the accessibility model that the compiler and runtime have always enforced. URLClassLoader::addUrl is intended only for subclasses; it is not intended to be accessed from outside the implementation, which is what you're doing. Over time, starting with Java 9 and continuing in later versions (including 17), access restrictions are increasingly recognized by reflection, with warnings, to give broken code a chance to migrate to something supportable.

The code in question only really ever worked accidentally; it depended on being able to break into an unsupported interface. Using setAccessible should be a clue. Sure, you can get into locked houses by breaking windows, but if you have to break a window (and it’s not your house), you should be aware of where the problem lies.

Look at it as glass-half-full; this accidentally-working code worked for a long time. But the bill has come due; it is time to fix your code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...