Skip to content

Instantly share code, notes, and snippets.

@ddrone
Created August 16, 2013 20:00
Show Gist options
  • Select an option

  • Save ddrone/6253074 to your computer and use it in GitHub Desktop.

Select an option

Save ddrone/6253074 to your computer and use it in GitHub Desktop.
import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
public class ProxyTest {
private static interface CatInterface {
public CatInterface printName();
public CatInterface sayMeow();
}
private static class Cat implements CatInterface {
public final String name;
private Cat(String name) {
this.name = name;
}
public Cat printName() {
System.out.println(name);
return this;
}
public Cat sayMeow() {
System.out.println(name + " says 'meow!'");
return this;
}
}
public static void main(String[] args) {
List<CatInterface> cats = Arrays.<CatInterface>asList(new Cat("Felix"), new Cat("Tiger"), new Cat("Tom"));
forEach(CatInterface.class, cats).printName().sayMeow();
}
@SuppressWarnings("unchecked")
public static <T> T forEach(Class<T> clazz, Collection<T> collection) {
T proxy = (T) Proxy.newProxyInstance(
ForEachInvocationHandler.class.getClassLoader(),
new Class[] { clazz },
new ForEachInvocationHandler<T>(clazz, collection)
);
return proxy;
}
private static class ForEachInvocationHandler<T> implements InvocationHandler {
private final Collection<T> collection;
private final Class<T> clazz;
private ForEachInvocationHandler(Class<T> clazz, Collection<T> collection) {
this.collection = collection;
this.clazz = clazz;
}
@Override
@SuppressWarnings("all")
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
List result = new ArrayList();
for (T elem : collection) {
result.add(method.invoke(elem, args));
}
return forEach(clazz, result);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment