From b1990138d8f6011415b53a4b2ac071e949380bf7 Mon Sep 17 00:00:00 2001 From: fullwall Date: Sun, 13 Jun 2021 13:41:36 +0800 Subject: [PATCH] Add getFirst API --- .../main/java/net/citizensnpcs/util/NMS.java | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/main/src/main/java/net/citizensnpcs/util/NMS.java b/main/src/main/java/net/citizensnpcs/util/NMS.java index c78475152..3cedb51b1 100644 --- a/main/src/main/java/net/citizensnpcs/util/NMS.java +++ b/main/src/main/java/net/citizensnpcs/util/NMS.java @@ -164,6 +164,32 @@ public class NMS { return null; } + private static Field getFirstFieldMatchingType(Class clazz, Class type) { + Field found = null; + for (Field field : clazz.getDeclaredFields()) { + if (field.getType() == type) { + found = field; + break; + } + } + if (found != null) { + found.setAccessible(true); + } + return found; + } + + public static MethodHandle getFirstGetter(Class clazz, Class type) { + try { + Field found = getFirstFieldMatchingType(clazz, type); + if (found == null) + return null; + return LOOKUP.unreflectGetter(found); + } catch (Exception e) { + Messaging.logTr(Messages.ERROR_GETTING_FIELD, type, e.getLocalizedMessage()); + } + return null; + } + public static MethodHandle getFirstMethodHandle(Class clazz, boolean log, Class... params) { if (clazz == null) return null; @@ -195,6 +221,18 @@ public class NMS { return null; } + public static MethodHandle getFirstSetter(Class clazz, Class type) { + try { + Field found = getFirstFieldMatchingType(clazz, type); + if (found == null) + return null; + return LOOKUP.unreflectSetter(found); + } catch (Exception e) { + Messaging.logTr(Messages.ERROR_GETTING_FIELD, type, e.getLocalizedMessage()); + } + return null; + } + public static GameProfileRepository getGameProfileRepository() { return BRIDGE.getGameProfileRepository(); }