DefaultObjectFactory implements ObjectFactory, Serializable { <T> T instantiateClass(Class<T> type, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) { try { Constructor<T> constructor; if (constructorArgTypes == null || constructorArgs == null) { constructor = type.getDeclaredConstructor(); if (!constructor.isAccessible()) { constructor.setAccessible(true); } return constructor.newInstance(); } constructor = type.getDeclaredConstructor(constructorArgTypes.toArray(new Class[constructorArgTypes.size()])); if (!constructor.isAccessible()) { constructor.setAccessible(true); } return constructor.newInstance(constructorArgs.toArray(new Object[constructorArgs.size()])); } catch (Exception e) { StringBuilder argTypes = new StringBuilder(); if (constructorArgTypes != null && !constructorArgTypes.isEmpty()) { for (Class<?> argType : constructorArgTypes) { argTypes.append(argType.getSimpleName()); argTypes.append(","); } argTypes.deleteCharAt(argTypes.length() - 1); } StringBuilder argValues = new StringBuilder(); if (constructorArgs != null && !constructorArgs.isEmpty()) { for (Object argValue : constructorArgs) { argValues.append(String.valueOf(argValue)); argValues.append(","); } argValues.deleteCharAt(argValues.length() - 1); } throw new ReflectionException("Error instantiating " + type + " with invalid types (" + argTypes + ") or values (" + argValues + "). Cause: " + e, e); } }  @Override T create(Class<T> type); @SuppressWarnings("unchecked") @Override T create(Class<T> type, List<Class<?>> constructorArgTypes, List<Object> constructorArgs); @Override void setProperties(Properties properties); @Override boolean isCollection(Class<T> type);  }
@Test public void instantiateClass() throws Exception { DefaultObjectFactory defaultObjectFactory = new DefaultObjectFactory(); TestClass testClass = defaultObjectFactory.instantiateClass(TestClass.class, Arrays.<Class<?>>asList(String.class, Integer.class), Arrays.<Object>asList("foo", 0)); Assert.assertEquals("myInteger didn't match expected", (Integer) 0, testClass.myInteger); Assert.assertEquals("myString didn't match expected", "foo", testClass.myString); }
@Test public void instantiateClassThrowsProperErrorMsg() { DefaultObjectFactory defaultObjectFactory = new DefaultObjectFactory(); try { defaultObjectFactory.instantiateClass(TestClass.class, Collections.<Class<?>>singletonList(String.class), Collections.<Object>singletonList("foo")); Assert.fail("Should have thrown ReflectionException"); } catch (Exception e) { Assert.assertTrue("Should be ReflectionException", e instanceof ReflectionException); Assert.assertTrue("Should not have trailing commas in types list", e.getMessage().contains("(String)")); Assert.assertTrue("Should not have trailing commas in values list", e.getMessage().contains("(foo)")); } }