Solved Get imports from string?

Discussion in 'Spigot Plugin Development' started by JackkGC, May 10, 2016.

  1. Is it possible to do NMS imports from strings (names)? Not:
    Code (Text):
    import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer;
    But:
    Code (Text):
    (not actually working)
    import.fromString("org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer");
    Would be great to make plugins version compatible!

    Is it possible in any way? Thanks already :D
     
  2. You'll either want to use reflection, or abstract classes separated into different packages depending on the minecraft version (v1_X_XX).
     
    • Agree Agree x 1
  3. I have to add that I never coded NMS really so I have no clue what are you talking about. Im sorry :rolleyes:
     
  4. Code (Text):

        private boolean hasSupportedVersion() {
            String packageName = this.getServer().getClass().getPackage().getName();
            String version = packageName.substring(packageName.lastIndexOf('.') + 1);
            try {
                final Class<?> clazz = Class.forName("net.pl3x.bukkit.pl3xsui.nms." + version + ".PluginChannelHandler");
                if (PluginChannel.class.isAssignableFrom(clazz)) {
                    pluginChannelHandler = (PluginChannel) clazz.getConstructor().newInstance();
                }
            } catch (Exception e) {
                return false;
            }
            return true;
        }
     
    Abstraction is key. ;)
     
    • Like Like x 1
  5. Basically the abstract classes is exactly what @BillyGalbreath just demonstrated.

    You create a "public abstract class NmsHandler" or whatever you want your classes to be called. Then inside sub-packages with the version string (v1_8_R3, v1_9, v1_9_R1, etc. are package names) you create a class with the same name that the Class.forName would look for.

    The other solution is to use reflection inside the one class you wish to do the work in, and make adjustments for past and future versions if anything changes (Entity NMS changes very frequently)
     
    • Agree Agree x 1
    • Useful Useful x 1
    • Useful Useful x 1
  6. Thats what I love Sigot forums for. Im german and tried german forums too but theyre unfriendly to newbees and hate to explain stuff. You guys make beginners learn and thats much better :D You are awesome!
     
    • Winner Winner x 1