user4118293
user4118293

Reputation:

JAVA - Run external jar file at start

I want to create an application that runs, and it has a folder which will contain jar files with minigames. I would like to create these minigames seperately as that will be easier to swap the games in and out. I just don't know how to load these jar files into my other already running application, so that I can just access the classes in the jar files and invoke the right methods with my annotations.

So, TL;DR, how do I add classes to my classpath on runtime?

With kind regards, Stan

Upvotes: 1

Views: 957

Answers (1)

zuckermanori
zuckermanori

Reputation: 1755

What you're doing is probably not the best way to go, in my opinion. With that said, here's an explanation that will help you achieve what you want:

Java works with ClassLoader which is a Java object that loads classes from a specific path, usually that would be the Java class_path. In order to dynamically load a jar, you can simply create a URLClassLoader with a URL referencing your jar, or alternatively add the jar URL to the current ClassLoader or to the system ClassLoader, depending on your use case. Once you loaded the jar, you'll be able to instantiate an instance of your Java class. Following is an example of creating a new Classloader with a specific jar:

URL url = new File(jarPath).toURI().toURL();
URLClassLoader classLoader = new URLClassLoader(url);
Object yourObject = Class.forName(className, true, classLoader).newInstance();

Of course, you should adapt the new instance creation to your class etc.

Upvotes: 1

Related Questions