WrapperGenerator implements IWrapperGenerator { @Override public <T> T generate(final Class<T> targetInterface) throws InvalidArgumentException, WrapperGeneratorException { T instance = null; if (null == targetInterface) { throw new InvalidArgumentException("Target class should not be null!"); } if (!targetInterface.isInterface()) { throw new InvalidArgumentException("Target class should be an interface!"); } try { instance = IOC.resolve( IOC.resolve(IOC.getKeyForKeyStorage(), targetInterface.getCanonicalName() + "wrapper") ); } catch (ResolutionException e) { } if (null != instance) { return instance; } try { Class<T> clazz = generateClass(targetInterface); IOC.register( IOC.resolve(IOC.getKeyForKeyStorage(), targetInterface.getCanonicalName() + "wrapper"), new ApplyFunctionToArgumentsStrategy( (arg) -> { try { return clazz.newInstance(); } catch (Throwable e) { throw new RuntimeException("Error on creation new instance.", e); } } ) ); return IOC.resolve( IOC.resolve(IOC.getKeyForKeyStorage(), targetInterface.getCanonicalName() + "wrapper") ); } catch (Throwable e) { throw new WrapperGeneratorException( "Could not implement wrapper interface because of the following error:", e ); } } WrapperGenerator(final ClassLoader classLoader); @Override T generate(final Class<T> targetInterface);  }
@Test public void checkCreationAndUsageWrapperByInterface() throws Exception { IWrapperGenerator wg = new WrapperGenerator(null); IWrapper w1 = wg.generate(IWrapper.class); assertNotNull(w1); IWrapper w2 = wg.generate(IWrapper.class); assertNotNull(w2); assertNotSame(w1, w2); }
@Test (expected = WrapperGeneratorException.class) public void checkOnIncorrectInterfaceWithoutReadValueException() throws Exception { IWrapperGenerator wg = new WrapperGenerator(null); wg.generate(IIncorrectWrapperWithoutReadValueException.class); }
@Test (expected = WrapperGeneratorException.class) public void checkOnIncorrectInterfaceWithoutChangeValueException() throws Exception { IWrapperGenerator wg = new WrapperGenerator(null); wg.generate(IIncorrectWrapperWithoutChangeValueException.class); }
@Test (expected = InvalidArgumentException.class) public void checkInvalidArgumentExceptionOnTargetInterfaceNull() throws Exception { IWrapperGenerator wg = new WrapperGenerator(null); wg.generate(null); fail(); }
@Test (expected = InvalidArgumentException.class) public void checkInvalidArgumentExceptionOnNotInterface() throws Exception { IWrapperGenerator wg = new WrapperGenerator(null); wg.generate(TestClass.class); fail(); }