public static Object createInstance(Class clazz, Object... args) { if (args.length == 1) { Object arg = args[0]; if (MetaClassHelper.isAssignableFrom(clazz, arg.getClass())) return arg; // IDEA: could do additional coercions here, like Groovy does when setting a property // (note that we don't know if we are setting a property or invoking a method): // int -> byte (at least if it fits), etc. } // IDEA: could support creation of collection types here if ((clazz.getModifiers() & Modifier.ABSTRACT) != 0) { String kind = clazz.isPrimitive() ? "primitive" : clazz.isInterface() ? "interface" : "abstract"; throw new RuntimeException(String.format( "Cannot instantiate %s type %s", kind, clazz.getName())); } // TODO: need exception handling for better error messages? return GroovyRuntimeUtil.invokeConstructor(clazz, args); } }
public static Object instantiate(Class<?> declaredType, Class<?> actualType, @Nullable List<Object> constructorArgs, boolean useObjenesis) { try { if (!declaredType.isInterface() && constructorArgs == null && useObjenesis && objenesisAvailable) { return ObjenesisInstantiator.instantiate(actualType); } return GroovyRuntimeUtil.invokeConstructor(actualType, constructorArgs == null ? null : constructorArgs.toArray()); } catch (Exception e) { String msg = constructorArgs == null && useObjenesis && !objenesisAvailable ? ". To solve this problem, put Objenesis 1.2 or higher on the class path (recommended), or supply " + "constructor arguments (e.g. 'constructorArgs: [42]') that allow to construct an object of the mocked type." : null; throw new CannotCreateMockException(declaredType, msg, e); } }