JavaCompilerInstanceSupplierFactory implements InstanceSupplierFactory { @Override public InstanceSupplier apply(Constructor<?> constructor) { Class<?> declaringClass = constructor.getDeclaringClass(); if (Modifier.isPublic(constructor.getModifiers())) { String packageName = declaringClass.getPackage().getName(); String simpleName = declaringClass.getSimpleName() + "$InstanceSupplier"; String newInstance = declaringClass.getName(); String name = declaringClass.getName() + "$InstanceSupplier"; String javaSource = StringFormatter.INSTANCE.format(TEMPLATE, packageName, simpleName, newInstance); InstanceJavaSource source = new InstanceJavaSource(name, simpleName, javaSource); Class<? extends InstanceSupplier> supplier = compilerFacade.apply(source); return reflections.newInstance(supplier); } LOGGER.fine(String.format("The constructor to the class %s is not public, using fallback with Reflectioin", declaringClass.getName())); return fallback.apply(constructor); } JavaCompilerInstanceSupplierFactory(JavaCompilerFacade compilerFacade, Reflections reflections, InstanceSupplierFactory fallback); @Override InstanceSupplier apply(Constructor<?> constructor);  }
@Test public void shouldCreateInstanceSupplier() { JavaCompilerInstanceSupplierFactory factory = new JavaCompilerInstanceSupplierFactory(compilerFacade, reflections, fallback); InstanceSupplier instanceSupplier = factory.apply(Foo.class.getConstructors()[0]); Assertions.assertNotNull(instanceSupplier); Object value = instanceSupplier.get(); Assertions.assertTrue(value instanceof Foo); }
@Test public void shouldUseFallbackWhenConstructorIsNotPublic() { JavaCompilerInstanceSupplierFactory factory = new JavaCompilerInstanceSupplierFactory(compilerFacade, reflections, fallback); Constructor<?> constructor = Faa.class.getDeclaredConstructors()[0]; constructor.setAccessible(true); InstanceSupplier instanceSupplier = factory.apply(constructor); Assertions.assertNotNull(instanceSupplier); Object value = instanceSupplier.get(); Assertions.assertTrue(value instanceof Faa); }