From 03f628aa03a6c35796bf252cc0aaa5e50182d3b1 Mon Sep 17 00:00:00 2001 From: tueem Date: Mon, 14 Oct 2024 00:17:34 +0200 Subject: [PATCH] add ReflectionUtil --- .../marinara/util/ReflectionUtil.java | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 lib/src/main/java/net/tomatentum/marinara/util/ReflectionUtil.java diff --git a/lib/src/main/java/net/tomatentum/marinara/util/ReflectionUtil.java b/lib/src/main/java/net/tomatentum/marinara/util/ReflectionUtil.java new file mode 100644 index 0000000..10365fe --- /dev/null +++ b/lib/src/main/java/net/tomatentum/marinara/util/ReflectionUtil.java @@ -0,0 +1,39 @@ +package net.tomatentum.marinara.util; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; + +import net.tomatentum.marinara.interaction.commands.annotation.ApplicationCommand; +import net.tomatentum.marinara.interaction.commands.annotation.SubCommand; + +public final class ReflectionUtil { + + public static boolean isAnnotationPresent(Method method, Class annotationClass) { + if (method.isAnnotationPresent(annotationClass) || method.getDeclaringClass().isAnnotationPresent(annotationClass)) + return true; + + return false; + } + + public static T getAnnotation(Method method, Class annotationClass) { + return method.isAnnotationPresent(annotationClass) ? + method.getAnnotation(annotationClass) : + method.getDeclaringClass().getAnnotation(annotationClass); + } + + public static void checkValidCommandMethod(Method method) { + if (method.isAnnotationPresent(ApplicationCommand.class) && + method.getDeclaringClass().isAnnotationPresent(ApplicationCommand.class)) { + throw new RuntimeException(method.getName() + ": Can't have ApplicationCommand Annotation on Class and Method"); + } + + if (!isAnnotationPresent(method, ApplicationCommand.class)) + throw new RuntimeException(method.getName() + ": Missing ApplicationCommand Annotation on either Class or Method"); + + if (!(method.isAnnotationPresent(SubCommand.class) && + isAnnotationPresent(method, ApplicationCommand.class))) { + throw new RuntimeException(method.getName() + ": Missing ApplicationCommand Annotation on either Method or Class"); + } + } + +}