Resource Using NMS with every version (Reflection)

Discussion in 'Spigot Plugin Development' started by Big_Bad_E, Sep 15, 2018.

  1. NOTE: THIS WAS JUST A SMALL SNIPPET I MADE CAUSE I HAD NOTHING TO DO

    Now here's the method:

    The idea is pretty simple.
    I get the version of Spigot by checking the package name from org.bukkit.craftbukkit.version.Server
    Then I load the class from net.minecraft.server.version.class
    I grab the method from the class and run it.

    Here's the code:
    Code (Text):
    private static String version = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3];

        public void runNMSMethod(String name, String className, Object object, Object[] params) {
            try {
                Class nmsClass = Class.forName("net.minecraft.server." + version + "." + className);
                List<Class<?>> classes = new ArrayList<>();
                for(Object object1 : params) {
                    classes.add(object1.getClass());
                }
                nmsClass.getMethod(name, (Class[]) classes.toArray()).invoke(object, params);
            } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    (I know it's static, but making a new instance for everything is a pain)

    Feel free to post any improvements/things I'm doing wrong.
     
    #1 Big_Bad_E, Sep 15, 2018
    Last edited: Sep 16, 2018 at 3:35 AM
  2. The best way to do it is on the wiki here
     
    • Useful Useful x 1
  3. It works, but I'd perfer not to have to go back and add more code to old plugins.
     
  4. Not really. I mean it's fine, code-wise, but the project setup in a single module isn't perfect.
     
  5. This will never work for primitives
     
  6. True, but reflection is slower.

    From reflection documentation:
    Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.
     
    #6 tchristofferson, Sep 15, 2018
    Last edited: Sep 15, 2018
  7. It's also easier to develop, as your code is checked by the compiler, so all public classes and methods at least exist.
     
    • Agree Agree x 1
  8. MiniDigger

    Supporter

    thats why you use multiple modules ;)
    like this https://github.com/MiniDigger/RideThaMobv3
     
    • Agree Agree x 1

Share This Page