Java 9 webstart JNLP Service produces IllegalAccess

The following code (to retrieve the base URL of a Java Web Start client application through the JNLP API) worked in Java 8, but did not execute when executed in (modular) Java 9 runtime:

Class<?> mclass = Class.forName("javax.jnlp.ServiceManager"); Method lookup = mclass.getMethod("lookup", new Class[]{String.class}); Object basicSvc = lookup.invoke(null, new Object[{"javax.jnlp.BasicService"}); Class<?> sclass = basicSvc.getClass(); Method getCodeBase = sclass.getMethod("getCodeBase", (Class[])null); URL codebase = (URL)getCodeBase.invoke(basicSvc, (Object[])null); // throws 

Results in

 java.lang.IllegalAccessException: class app.App cannot access class com.sun.jnlp.BasicServiceImpl (in module jdk.javaws) because module jdk.javaws does not export com.sun.jnlp to unnamed module @7202a0fa at java.base/jdk.internal.reflect.Reflection.newIllegalAccessException at java.base/java.lang.reflect.AccessibleObject.checkAccess at java.base/java.lang.reflect.Method.invoke at app.App.init 

How can this be fixed?

+1
source share
1 answer

As discussed in the previous more general question , the problem is that the second reflection method is not determined by the public API class, but by a private implementation, which does not work, because accessibility rules 9 apply.

The fix is ​​to use the getCodeBase method for the public interface instead:

 Class<?> sclass = Class.forName("javax.jnlp.BasicService"); 

It also avoids the reflection of an anti-pattern for working with dynamic defining classes.

Using a static implementation would also avoid this problem (however, this problem has a problem that requires javaws.jar , which may not be easy to get in some build environments).

 import javax.jnlp.BasicService; import javax.jnlp.ServiceManager; BasicService basicSvc = (BasicService)ServiceManager.lookup("javax.jnlp.BasicService"); URL u = basicSvc.getCodeBase(); 

Thanks to @Holger to test the reflection implementation and @Alan Bateman , guessing what the real problem was not seeing the code. Separate the two questions posed by @nicolai , which makes it a lot cleaner.

+4
source

Source: https://habr.com/ru/post/1272492/


All Articles