FunctionalReflection { public static <T> T newProxy(TypeToken<T> enclosingType, Function<Invocation, Object> invocationFunction) { checkNotNull(enclosingType, "enclosingType"); checkNotNull(invocationFunction, "invocationFunction"); return newProxy(enclosingType.getRawType(), new FunctionalInvocationHandler<T>(enclosingType, invocationFunction)); }  static T newProxy(TypeToken<T> enclosingType, Function<Invocation, Object> invocationFunction); static T newProxy(Class<T> enclosingType, Function<Invocation, Object> invocationFunction);  }
@SuppressWarnings("unchecked") @Test(expectedExceptions = UnsupportedOperationException.class) public void testNullArgsAreAllowedAndUnmodifiable() { final Function<Invocation, Object> test = new Function<Invocation, Object>() { public Object apply(Invocation e) { assertNotNull(e.getArgs()); assertNull(e.getArgs().get(0)); e.getArgs().add("foo"); throw new AssertionError("shouldn't be able to mutate the list!"); } }; FunctionalReflection.newProxy(Set.class, test).add(null); }
@SuppressWarnings("unchecked") @Test(expectedExceptions = UnsupportedOperationException.class) public void testImmutableListWhenArgsAreNotNull() { final Function<Invocation, Object> test = new Function<Invocation, Object>() { public Object apply(Invocation e) { assertNotNull(e.getArgs()); assertTrue(e.getArgs() instanceof ImmutableList); assertEquals(e.getArgs().get(0), "foo"); e.getArgs().add("bar"); throw new AssertionError("shouldn't be able to mutate the list!"); } }; FunctionalReflection.newProxy(Set.class, test).add("foo"); }
@Test(expectedExceptions = IOException.class, expectedExceptionsMessageRegExp = "io") public void testPropagatesDeclaredException() throws IOException { final Function<Invocation, Object> test = new Function<Invocation, Object>() { public Object apply(Invocation e) { throw new RuntimeException(new IOException("io")); } }; Closeable closeable = FunctionalReflection.newProxy(Closeable.class, test); closeable.close(); }
@Test(expectedExceptions = AssertionError.class, expectedExceptionsMessageRegExp = "assert") public void testPropagatesError() throws IOException { final Function<Invocation, Object> test = new Function<Invocation, Object>() { public Object apply(Invocation e) { throw new AssertionError("assert"); } }; Closeable closeable = FunctionalReflection.newProxy(Closeable.class, test); closeable.close(); }