diff --git a/Plugin/src/main/java/com/willfp/ecoenchants/enchantments/EcoEnchant.java b/Plugin/src/main/java/com/willfp/ecoenchants/enchantments/EcoEnchant.java index 2e94ff0a..eebb4be6 100644 --- a/Plugin/src/main/java/com/willfp/ecoenchants/enchantments/EcoEnchant.java +++ b/Plugin/src/main/java/com/willfp/ecoenchants/enchantments/EcoEnchant.java @@ -1,10 +1,12 @@ package com.willfp.ecoenchants.enchantments; import com.earth2me.essentials.Enchantments; +import com.earth2me.essentials.Essentials; import com.willfp.ecoenchants.Main; import com.willfp.ecoenchants.config.ConfigManager; import com.willfp.ecoenchants.config.configs.EnchantmentConfig; import com.willfp.ecoenchants.nms.Target; +import com.willfp.ecoenchants.util.EssentialsUtils; import org.apache.commons.lang.WordUtils; import org.apache.commons.lang.reflect.FieldUtils; import org.bukkit.Material; @@ -102,9 +104,12 @@ public abstract class EcoEnchant extends Enchantment implements Listener { Enchantment.registerEnchantment(this); if(Main.hasEssentials) { - Map essentialsMap = (Map) FieldUtils.readDeclaredStaticField(Enchantments.class, "ENCHANTMENTS", true); - essentialsMap.remove(this.getName()); - essentialsMap.put(this.getName(), this); + Map essentialsMap = EssentialsUtils.getEnchantmentsMap(); + if (essentialsMap != null) { + String key = this.getKey().getKey(); + essentialsMap.remove(key); + essentialsMap.put(key, this); + } } } catch (NoSuchFieldException | IllegalAccessException ignored) {} } diff --git a/Plugin/src/main/java/com/willfp/ecoenchants/util/EssentialsUtils.java b/Plugin/src/main/java/com/willfp/ecoenchants/util/EssentialsUtils.java new file mode 100644 index 00000000..b0539267 --- /dev/null +++ b/Plugin/src/main/java/com/willfp/ecoenchants/util/EssentialsUtils.java @@ -0,0 +1,37 @@ +package com.willfp.ecoenchants.util; + +import com.earth2me.essentials.Enchantments; +import org.apache.commons.lang.reflect.FieldUtils; +import org.bukkit.Bukkit; +import org.bukkit.enchantments.Enchantment; +import org.jetbrains.annotations.Nullable; + +import java.util.Map; + +public class EssentialsUtils { + private static Map essentialsEnchantmentsMap; + private static boolean hasCheckedEnchantmentsMap; + + @Nullable + public static Map getEnchantmentsMap() { + if (hasCheckedEnchantmentsMap) return essentialsEnchantmentsMap; + + if (Bukkit.getPluginManager().isPluginEnabled("Essentials")) { + try { + Class essEnchantmentsClass = Enchantments.class; + + Object enchantments = FieldUtils.readDeclaredStaticField(essEnchantmentsClass, "ENCHANTMENTS", true); + if (enchantments instanceof Map) { + hasCheckedEnchantmentsMap = true; + //noinspection unchecked - we know the type of it + return essentialsEnchantmentsMap = (Map) enchantments; + } + } catch (IllegalAccessException e) { + hasCheckedEnchantmentsMap = true; + return null; + } + } + hasCheckedEnchantmentsMap = true; + return null; + } +}