Last active
December 21, 2015 21:27
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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?