Reputation: 2197
So I was just playing with the idea of user plugins. I wrote a simple class that prints out a String. Then I wrote an interface which requires a single method for editing that String. Now, Id like to have the user be able to insert a Jar file into a folder (packaged with the program) and my program reads it in, and uses it as a class which implements the interface which I created. So basically I am looking for a way of reading in a jar files contents, and using its class as one of my programs classes. Apologies in advanced for any incorrect terminology, I am very new to this. If this is the wrong way to approaching the problem let me know, Im open to a better way. Thanks!
Class:
public class Project {
static String message = "default message";
public static void main(String args[]) {
System.out.println(message);
}
}
Interface:
public interface Mod {
void modifyText(String moddedMessage);
}
User Plugin
public class UserMod implements Mod {
public void modifyText(String moddedMessage) {
moddedMessage = "New Message";
Project.message = moddedMessage;
}
}
Upvotes: 0
Views: 1668
Reputation: 26
Please correct me if I am wrong, but you simply wish to use an outside java class from a .jar file?
If that is the case, you should simply use it in your program and then reference it's jar to the java compiler when of compilation (considering there is no packaging of the mentioned classes, as you didn't specified any of that - see Java packages - if there were packages, you would need to import the UserMod class or use it's fully qualified name). E.g.:
public class Project {
static String message = "default message";
public static void main(String args[]) {
String newMessage = "new message";
UserMod userMod = new UserMod();
userMod.modifyText(newMessage());
System.out.println(message);
}
}
Then, compiling on the command line and running:
javac -cp UserMod.jar Project.java
java Project
However, you could simply ask the user to pass the text you want to print as a parameter to the program, like so (the args array is simply an array of strings passed in as parameters to the program):
public class Project {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("No parameters. Please give me something to print!!");
} else {
for (String parameter : args) {
System.out.println(parameter);
}
}
}
}
Then, compile and run it with any parameters you like:
javac Project.java
java Project "new message"
>> new message
Upvotes: 1