Dynamically loading jar from arbitrary url

285 Views Asked by At

Recently AWS Lambda added support for Java.
While this is great news, this come with a pretty severe limitation to the size of the code (50MB compressed). While this may be fine for other languages, Java uberjars can easily beat that.

So I've been toying with the idea of having a small loader that pull in, at runtime, a bigger jar from somewhere else. (set aside if this is a good idea or not for a moment).

From my initial research seems that a Custom Class Loader is the way to go. This is probably a no go for AWS Lambda.

Is there any other creative way this could be achieved?

1

There are 1 best solutions below

1
On BEST ANSWER

I think ClassLoader, and more precisely URLClassLoader, is the way to go, and I don't know of any other solution to load code at runtime.

The class loader does not even have to be custom. It works with just a few lines of code, as demonstrated in this post.

If the jar files you will load fulfill a particular service for your application, also consider the handy ServiceLoader. It works on the same principle (in fact, you can pass it directly a ClassLoader), but makes it transparent to instantiate objects from the dynamically loaded library. Otherwise, you would have to get your hands a bit dirty, using something like:

Object main = loader.loadClass("Main", true).newInstance();