From 32c1881d95d03bdb0de62ba79a22d775e895e8fa Mon Sep 17 00:00:00 2001 From: Roman Zhuravlev Date: Sat, 20 Sep 2025 01:32:05 +0500 Subject: [PATCH] Add reflection methods for Constructor --- .../java/org/zhdev/util/ReflectionUtils.java | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/common/src/main/java/org/zhdev/util/ReflectionUtils.java b/common/src/main/java/org/zhdev/util/ReflectionUtils.java index dd71599..900761e 100644 --- a/common/src/main/java/org/zhdev/util/ReflectionUtils.java +++ b/common/src/main/java/org/zhdev/util/ReflectionUtils.java @@ -5,7 +5,9 @@ import org.zhdev.reflection.MethodSearcher; import java.io.File; import java.io.IOException; +import java.lang.reflect.Constructor; import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Enumeration; import java.util.function.Consumer; @@ -25,6 +27,12 @@ public class ReflectionUtils { return field; } + private static Constructor getConstructor0(Class type, Class... parameterTypes) throws NoSuchMethodException { + Constructor constructor = type.getDeclaredConstructor(parameterTypes); + constructor.setAccessible(true); + return constructor; + } + private static boolean compareParameters(Class[] required, Class... parameters) { if (required.length != parameters.length) { return false; @@ -174,6 +182,22 @@ public class ReflectionUtils { } } + public static Constructor getConstructor(Class type, Class... parameterTypes) throws NoSuchMethodError { + try { + return getConstructor0(type, parameterTypes); + } catch (NoSuchMethodException e) { + throw new NoSuchMethodError(e.getMessage()); + } + } + + public static Object newInstance(Constructor constructor, Object... args) throws NoSuchMethodError { + try { + return constructor.newInstance(args); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException(e); + } + } + public static void forEachClass(ClassLoader loader, JarFile jarFile, String packageName, Consumer> consumer) { for (Enumeration entry = jarFile.entries(); entry.hasMoreElements(); ) { JarEntry jarEntry = entry.nextElement();