Learning reflection

Discussion in 'Plugin Development' started by JanTuck, Jan 17, 2017.

Thread Status:
Not open for further replies.
  1. Offline

    JanTuck

    Is there an easier way to do reflection?

    Code:java
    1. public static Class<?> getBukkitClass(String name) {
    2. String version = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3];
    3. try {
    4. return Class.forName("org.bukkit.craftbukkit." + version + "." + name);
    5. }
    6. catch (Exception e) {
    7. StackTraceCore.getStackTraceCore().printTrace(e);
    8. return null;
    9. }
    10. }
    11.  
    12.  
    13. public static Object getName(ItemStack itemStack)
    14. {
    15. Object craftItemStack = null;
    16. Class<?> bukkitClass = getBukkitClass("inventory.CraftItemStack");
    17. try {
    18. craftItemStack = bukkitClass.getMethod("asNMSCopy", ItemStack.class).invoke(bukkitClass, itemStack);
    19. Class<?> craftitemStackClass = craftItemStack.getClass();
    20. return craftitemStackClass.getDeclaredMethod("getName").invoke(craftItemStack);
    21. } catch (Exception e) {
    22. StackTraceCore.getStackTraceCore().printTrace(e);
    23. }
    24. return "";
    25. }
     
  2. @JanTuck
    Apart from the fact that you could create a few more util methods to remove the exception catching completely, not really.
     
  3. Offline

    JanTuck

  4. @JanTuck
    Well, there are a couple possibilities:
    • This method might not have existed when that thread was made.
    • This method is NMS, so it might change in different versions leading to a lot of hassle
    • If the ItemStack has a custom name, it'll return that instead.
     
Thread Status:
Not open for further replies.

Share This Page