Look at how getDeclaredConstructors()
is defined:
public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
The Class<?>...
notation means that the method is variadic. It takes a list of Class objects as arguments, and there are two ways to provide that list:
You can list the objects as separate arguments:
Constructor<?> ctor = getDeclaredConstructor(String.class, String.class, Integer.class, etc)
You can construct an array and pass the array as a single argument
Class<?>[] classes = new Class<?>[3];
classes[0] = String.class;
...
Constructor<?> ctor = getDeclaredConstructor(classes);
To find a constructor without knowing ahead of time how many parameters it has or what their types are, you'd use the second method--construct an array describing the parameter list that you're looking for, then call getDeclaredConstructor()
with that array as a parameter. Here's an example:
static <T> T construct(Class<T> aClass, Object...args)
throws NoSuchMethodException, SecurityException,
InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
Class<?>[] classes = new Class<?>[args.length];
for (int ii = 0; ii < args.length; ++ii) {
classes[ii] = args[ii].getClass();
}
Constructor<T> ctor = aClass.getDeclaredConstructor(classes);
return ctor.newInstance(args);
}
...
String abc = construct(String.class, "abc");
URL google = construct(URL.class, "http", "google.com", "/");