Skip to content

Instantly share code, notes, and snippets.

@fdoyle
Last active December 21, 2015 21:27
Show Gist options
  • Save fdoyle/543bbf42d45a981d2266 to your computer and use it in GitHub Desktop.
Save fdoyle/543bbf42d45a981d2266 to your computer and use it in GitHub Desktop.
Use case: You have an object with setListener, and you have to listeners. Do Combiner.combine(listener1, listener2), with any given type, and it'll do what you want
package com.lacronicus.combodriver;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* Created by fdoyle on 12/17/15.
*/
public class ListenerCombiner {
public static <T> T combine(T arg, T... args) {
InvocationHandler handler = new VarHandler(arg, args);
return (T) Proxy.newProxyInstance(args[0].getClass().getClassLoader(),
arg.getClass().getInterfaces(),
handler);
}
static class VarHandler implements InvocationHandler {
Object[] objects;
Object object;
public VarHandler(Object arg, Object... args) {
this.objects = args;
this.object = arg;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object firstReturnValue = method.invoke(object, args);
for (Object object : objects) {
method.invoke(object, args);
}
return firstReturnValue;
}
}
}
//both of these execute
v.setOnClickListener(ListenerCombiner.combine(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("TAG", "first listener");
}
},
new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("TAG", "second listener");
}
}
));
//this is not limited to click listeners. it will work with any type
@fdoyle
Copy link
Author

fdoyle commented Dec 17, 2015

Doesn't handle return values very well, but most android listeners don't really have those.

Maybe have a combine method for the return values?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment