views:

541

answers:

3

If I'm running a signed Java applet, can I download additional classes from remote sources (in the same domain, maybe even the same host) and run them?

I'd like to do this without changing pages or even stopping the current applet. Of course, the total size of all classes is too large to load them all at once.

Is there a way to do this? And is there a way to do this with signed applets and preserve their "confidence" status?

A: 

Sounds like it should be possible (but I've never done it). Have you already had a look at Remote Method Invocation (RMI)?

John Smithers
RMI is not the direction I'm looking for, but thanks anyway.
+4  A: 

I think classes are lazy loaded in applets. being loaded on demand.

Anyway, if the classes are outside of a jar you can simply use the applet classloader and load them by name. Ex:

ClassLoader loader = this.getClass().getClassLoader();
Class clazz = loader.loadClass("acme.AppletAddon");

If you want to load classes from a jar I think you will need to create a new instance of URLClassLoader with the url(s) of the jar(s).

URL[] urls = new URL[]{new URL("http://localhost:8080/addon.jar")};
URLClassLoader loader = URLClassLoader.newInstance(urls,this.getClass().getClassLoader());
Class clazz = loader.loadClass("acme.AppletAddon");

By default, applets are forbidden to create new classloaders. But if you sign your applet and include permission to create new classloaders you can do it.

jassuncao
Thank you, URLClassLoader seems like just what I wanted. I'll just need to make sure I can keep the signing chain intact.
It worked after the parent (loader) applet was signed. But the child (loaded) jars, even though they are signed, don't get security permissions.
+2  A: 

Yes, you can open URL connections to the host you ran your applet from. You can either create a classloader with HTTP urls, or download the classes (as jars) to the user's machine and create a classloader with those jars in the classpath. The applet won't stop and you don't need to load another page.

Regarding the second part of your question about confidence, once the user has granted access to your applet it can download anything, yes anything, it wants to the local machine. You can probably inform the user as to what it's doing, if your UI design permits this.

Hope this helps.

Brilliant, thank you. I wish I could accept/merge both answers.
Unfortunately, as I commented on jassuncao's answer, the loaded applet so far doesn't have the appropriate permissions.