Here you can find the source of newInstanceFromUnknownArgumentTypes(Class
public static <T> T newInstanceFromUnknownArgumentTypes(Class<T> cls, Object[] args)
//package com.java2s; //License from project: Apache License import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Arrays; import java.util.stream.Collectors; public class Main { public static <T> T newInstanceFromUnknownArgumentTypes(Class<T> cls, Object[] args) { try {// ww w . j a va 2s.c om return cls.getDeclaredConstructor(getArgumentTypesFromArgumentList(args)).newInstance(args); } catch (InstantiationException | InvocationTargetException | IllegalAccessException ie) { throw new RuntimeException(ie); } catch (NoSuchMethodException nsme) { // Now we need to find a matching primitive type. // We can maybe cheat by running through all the constructors until we get what we want // due to autoboxing Constructor[] ctors = Arrays.stream(cls.getDeclaredConstructors()) .filter(c -> c.getParameterTypes().length == args.length).toArray(Constructor[]::new); for (Constructor<?> ctor : ctors) { try { return (T) ctor.newInstance(args); } catch (Exception e) { // silently drop exceptions since we are brute forcing here... } } String argTypes = Arrays.stream(args).map(Object::getClass).map(Object::toString) .collect(Collectors.joining(", ")); String availableCtors = Arrays.stream(ctors).map(Constructor::toString) .collect(Collectors.joining(", ")); throw new RuntimeException( "Couldn't find a matching ctor for " + argTypes + "; available ctors are " + availableCtors); } } /** * Extract argument types from a string that represents the method * signature. * @param args Signature string * @return Array of types */ public static Class[] getArgumentTypesFromArgumentList(Object[] args) { return Arrays.stream(args).map(Object::getClass).toArray(Class[]::new); } }