Add reflection methods for Constructor

This commit is contained in:
Roman Zhuravlev 2025-09-20 01:32:05 +05:00
parent 23acc54f16
commit 32c1881d95

View file

@ -5,7 +5,9 @@ import org.zhdev.reflection.MethodSearcher;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.function.Consumer; import java.util.function.Consumer;
@ -25,6 +27,12 @@ public class ReflectionUtils {
return field; 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) { private static boolean compareParameters(Class<?>[] required, Class<?>... parameters) {
if (required.length != parameters.length) { if (required.length != parameters.length) {
return false; 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<Class<?>> consumer) { public static void forEachClass(ClassLoader loader, JarFile jarFile, String packageName, Consumer<Class<?>> consumer) {
for (Enumeration<JarEntry> entry = jarFile.entries(); entry.hasMoreElements(); ) { for (Enumeration<JarEntry> entry = jarFile.entries(); entry.hasMoreElements(); ) {
JarEntry jarEntry = entry.nextElement(); JarEntry jarEntry = entry.nextElement();