简体   繁体   中英

Dynamically loading jar from arbitrary url

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?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM