Allow BOPReflectionHelper.construct() to work with arguments which are castable to the declared constructor arguments

This commit is contained in:
Cheeserolls 2015-05-23 16:37:59 +01:00
parent b36c0b0700
commit 08c80171a3
1 changed files with 26 additions and 6 deletions

View File

@ -17,13 +17,8 @@ public class BOPReflectionHelper
// Works on constructors which aren't usually accessible
public static <T> T construct(Class<T> clazz, Object... args)
{
Constructor<T> constructor = getConstructor(clazz, args);
try {
Class<?>[] argClasses = new Class<?>[args.length];
for (int i = 0; i < args.length; i++)
{
argClasses[i] = args[i].getClass();
}
Constructor<T> constructor = clazz.getDeclaredConstructor(argClasses);
constructor.setAccessible(true);
return constructor.newInstance(args);
} catch (Exception e) {
@ -31,4 +26,29 @@ public class BOPReflectionHelper
}
}
public static <T> Constructor<T> getConstructor(Class<T> clazz, Object... args)
{
int len = args.length;
for (Constructor constructor : clazz.getDeclaredConstructors())
{
Class[] constructorArgTypes = constructor.getParameterTypes();
if (constructorArgTypes.length == len)
{
boolean match = true;
for (int i = 0; i < len; i++)
{
if (!constructorArgTypes[i].isInstance(args[i]))
{
match = false;
}
}
if (match)
{
return (Constructor<T>)constructor;
}
}
}
return null;
}
}