Skip to content

Instantly share code, notes, and snippets.

@KoalaOnCaffeine
Last active February 16, 2024 17:16
Show Gist options
  • Save KoalaOnCaffeine/a891beaccd03552ce78e488b7ed7be6a to your computer and use it in GitHub Desktop.
Save KoalaOnCaffeine/a891beaccd03552ce78e488b7ed7be6a to your computer and use it in GitHub Desktop.
Constructor dependency injection
public final class CustomCommandPlugin extends JavaPlugin {
@Override
public final void onEnable() {
getCommand("command").setExecutor(new CommandClass(getConfig().getString("Hello-Message")));
// creating a new instance of the command class, passing in the hello message parameter as the String from the command class' constructor.
// getCommand being an inherited method from JavaPlugin.
// setExecutor being a method which every PluginCommand has, defining where it will run to.
// new CommandClass being the constructor of the class below.
// getConfig().getString("Hello-Message"); being a String located in the config, if this string is not there:
// IF THE STRING IS NOT THERE YOU WILL GET A NULL POINTER EXCEPTION
}
}
public final class CommandClass implements CommandExecutor {
private final String helloMessage;
// declaring a field of the string hello messsage, local to this class.
// The constructor of the "CommandClass" class, this will be called when you use "new CommandClass", and you
// will have to provide it with parameters, in this case a string, if you have added them into the constructor.
// String helloMessage could be changed to anything, for example you could change this to a Runnable, which you
// could execute using Runnable#run etc.
public CommandClass(String helloMessage) {
this.helloMessage = helloMessage;
// setting the helloMessage object, passed from the constructor to the local one in the class
// this, refering to the current class, not a static, or global, variable.
// this.helloMessage, refering to the current class' variable, named helloMessage
// helloMessage, refering to the string passed in from the constructor.
}
// The method for the command, called when a player runs the command which links back to here.
@Override// *Exerosis quirk*
public boolean onCommand(CommandSender sender, Command command, String $, String[] args) {
// Sending the sender a message, usign the passed in string from the constructor.
sender.sendMessage(helloMessage);
return true;
}
}
@linpan0
Copy link

linpan0 commented Mar 29, 2019

System.out.println("Excellent example of Dependency Injection A+");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment