Search code examples
javapythonpython-2.7jythonminecraft

Is it possible to convert this Java code to Jython for a Minecraft Plugin?


I was looking at this video to find some information on making Minecraft Plugins. https://youtu.be/r4W4drYdb4Q All plugins are made with Java. Since I program with Python I was wondering if it is possible to make a Plugin similar to the one seen in the video but with Jython. I am not sure if this is possible but I started trying.

When programming Java most people use Eclipse and there is a button that says "Add external Jar" and that is where you input the spigot jar file. From what I understand I can do that with:

import sys
sys.path.append("spigot-1.15.2.jar")

in Jython. Then there comes the tricky part. How would I go about converting this: Code Part 1

Code Part 2

From what I thought I needed to do was something like:

from org.bukkit.plugin.java import JavaPlugin

class Main(JavaPlugin):
    def onEnable():
        pass
        #what do I put here?
    def onDisable():
        pass
        #what do I put here?

But I don't think I am properly converting the Java code to Jython. What would be the proper way to convert the code from Java to Jython? Thanks very much!


Solution

  • From my understanding you want to interact from your Jython code with a Java class which extends JavaPlugin.

    For this I suggest you write a thin wrapper in Java which then calls your Jython code where you do the heavy lifting in your familiar language. A skeleton of the wrapper could look like this:

    package {$GroupName}.{$ArtifactName};
    
    import org.bukkit.plugin.java.JavaPlugin;
    import org.python.util.PythonInterpreter;
    
    public final class {$ArtifactName} extends JavaPlugin {
        @Override
        public void onEnable() {
            PythonInterpreter pi = new PythonInterpreter();
            pi.execfile("enable.py"); // enable.py is the Jython file with the enable stuff
        }
    
        @Override
        public void onDisable() {
            PythonInterpreter pi = new PythonInterpreter();
            pi.execfile("disable.py"); // enable.py is the Jython file with the disable stuff
        }
    
    }
    

    Be aware that instantiating PythonInterpreter is rather slow, so you'd be better off with a pattern where you do this only once. Plus then you can share data between enable and disable!

    For more details and other options (like having the Jython stuff in one file and calling into it via pi.exec) look at Chapter 10: Jython and Java Integration in the Jython Book.

    Also keep in mind when coding away: Jython is only Python 2.7!!!