From 8a2dbee1ba9b3f7e3d0251e56a465fc2d5746b08 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Florian=20N=C3=BCcke?= Date: Tue, 1 Dec 2020 02:39:37 +0100 Subject: [PATCH] Add ability to check for methods without instantiating them. --- .../cil/oc2/api/device/object/Callbacks.java | 28 +++++++++++++++++-- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/src/main/java/li/cil/oc2/api/device/object/Callbacks.java b/src/main/java/li/cil/oc2/api/device/object/Callbacks.java index 4d023b79..f33cc39f 100644 --- a/src/main/java/li/cil/oc2/api/device/object/Callbacks.java +++ b/src/main/java/li/cil/oc2/api/device/object/Callbacks.java @@ -43,9 +43,7 @@ public final class Callbacks { * @return the list of methods extracted from the specified object. */ public static List collectMethods(final Object methodContainer) { - final List reflectedMethods = METHOD_BY_TYPE.computeIfAbsent(methodContainer.getClass(), c -> Arrays.stream(c.getMethods()) - .filter(m -> m.isAnnotationPresent(Callback.class)) - .collect(Collectors.toList())); + final List reflectedMethods = getMethods(methodContainer.getClass()); final ArrayList methods = new ArrayList<>(); for (final Method method : reflectedMethods) { @@ -58,4 +56,28 @@ public final class Callbacks { return methods; } + + /** + * Returns whether any {@link Callback} annotated methods are present on the specified + * object without creating bound {@link DeviceMethod} instances. + *

+ * The specified {@code object} can be an instance or a {@link Class}. + * + * @param object the object to check for methods on. + * @return {@code true} if any methods were found on the object; {@code false} otherwise. + */ + public static boolean hasMethods(final Object object) { + if (object instanceof Class) { + return !getMethods((Class) object).isEmpty(); + + } else { + return !getMethods(object.getClass()).isEmpty(); + } + } + + private static List getMethods(final Class type) { + return METHOD_BY_TYPE.computeIfAbsent(type, c -> Arrays.stream(c.getMethods()) + .filter(m -> m.isAnnotationPresent(Callback.class)) + .collect(Collectors.toList())); + } }