From 1c7c5936909e5677ce7067192ce8dab29c0cd92d Mon Sep 17 00:00:00 2001 From: Brianna Date: Tue, 24 Mar 2020 08:29:58 -0400 Subject: [PATCH] CompatibleHand --- .../core/compatibility/CompatibleHand.java | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Core/src/main/java/com/songoda/core/compatibility/CompatibleHand.java diff --git a/Core/src/main/java/com/songoda/core/compatibility/CompatibleHand.java b/Core/src/main/java/com/songoda/core/compatibility/CompatibleHand.java new file mode 100644 index 00000000..63c992a5 --- /dev/null +++ b/Core/src/main/java/com/songoda/core/compatibility/CompatibleHand.java @@ -0,0 +1,45 @@ +package com.songoda.core.compatibility; + +import org.bukkit.inventory.EquipmentSlot; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; + +/** + * Get which hand is being used. + * + * @author Brianna + * @since 2020-03-24 + */ +public enum CompatibleHand { + + MAIN_HAND, OFF_HAND; + + private static Map methodCache = new HashMap<>(); + + public static CompatibleHand getHand(Object event) { + try { + Class clazz = event.getClass(); + String className = clazz.getName(); + Method method; + if (methodCache.containsKey(className)) { + method = methodCache.get(className); + } else { + method = clazz.getDeclaredMethod("getHand"); + methodCache.put(className, method); + } + EquipmentSlot slot = (EquipmentSlot) method.invoke(event); + if (slot == EquipmentSlot.OFF_HAND) + return OFF_HAND; + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + return MAIN_HAND; + } + return MAIN_HAND; + } + + public static CompatibleHand getHand(EquipmentSlot equipmentSlot) { + return equipmentSlot == EquipmentSlot.HAND ? MAIN_HAND : OFF_HAND; + } +}