Solved Accessing plugin version in class that doesn't extend JavaPlugin

Discussion in 'Spigot Plugin Development' started by SemCrafter, Jul 4, 2021.

  1. Hey people!

    I'm trying to make a command that sends the plugin version to the command sender.
    I've researched how to do this and I found that you need to use something like:

    PluginDescriptionFile pdf = this.getDescription();
    pdf.getVersion();

    However, this doesn't work for me since I'm using a command in it's own class which doesn't extend JavaPlugin. Therefore, this.getDescription does not get recognized.

    So my question is: How do I get information like the plugin version and use it in a class that doesn't extend JavaPlugin?

    Thanks!

    PS: I am new to Java.
     
  2. The fastest way is to use static field in your main class, but this is not the best way.
    Otherwise you can encapsulate your main class in your command class.

    like so:

    Code (Java):
    public class CommandClass implements ....{

      private MainClass object;

      public CommandClass(MainClass object){
     
        this.object = object;
     
      }

      .....

    }
    in your MainClass, in onEnable method, when you register the command, add "this" in the CommandClass constructor, like this:
    Code (Java):
    Bukkit.getServer().getPluginCommand(commandName).setExecutor(new CommandClass(this));
     
  3. My solution for this is to create a public static main getPlugin in the main

    Code (Java):
    public class Main extends JavaPlugin {

       private static Main plugin;

       @Override
       public void onEnable() {
           plugin = this;
       }

       public static Main getPlugin() {
           return plugin;
       }

    }
    and then in the Command class you can call it with

    Code (Java):
    Main.getPlugin().getDescription().getVersion();
     
  4. Sorry, but I don't think I understand the objects. I'm new to Java.

    Thank you so much! This worked for me. :D

    Edit: Ok so yea it's not the best way so im gonna try to learn the way MrBast told.
     
    #4 SemCrafter, Jul 4, 2021
    Last edited: Jul 4, 2021
  5. It doesnt matter at all which which of the two methods you use.