Skip to content

Instantly share code, notes, and snippets.

@trekawek
Created March 22, 2014 17:28
Show Gist options
  • Save trekawek/9711080 to your computer and use it in GitHub Desktop.
Save trekawek/9711080 to your computer and use it in GitHub Desktop.
Proxy objects created by the Recorder saves all method invocations. Saved invocations can be replayed using play() method. It's possible to record/replay invocations on a few different interfaces.
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MethodInvocation {
private final Method method;
private final Object[] args;
private final Class<?> clazz;
public MethodInvocation(Method method, Object[] args, Class<?> clazz) {
this.method = method;
this.args = args;
this.clazz = clazz;
}
public void invoke(Object[] receivers) throws IllegalAccessException, IllegalArgumentException,
InvocationTargetException, NoSuchMethodException, SecurityException {
for (Object o : receivers) {
if (o != null && clazz.isAssignableFrom(o.getClass())) {
method.invoke(o, args);
}
}
}
@Override
public String toString() {
return String.format("%s#%s(%s)", clazz.getSimpleName(), method.getName(), args);
}
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Recorder {
private static final Logger LOG = LoggerFactory.getLogger(Recorder.class);
private final List<MethodInvocation> recordedActions;
public Recorder() {
this.recordedActions = new ArrayList<>();
}
@SuppressWarnings("unchecked")
public <T> T getProxy(final Class<T> clazz) {
return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class<?>[] { clazz },
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
recordedActions.add(new MethodInvocation(method, args, clazz));
return null;
}
});
}
public void play(Object... receivers) {
for (MethodInvocation i : recordedActions) {
try {
i.invoke(receivers);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
LOG.error("Can't invoke method", e);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment