main 类:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class Main
{
private Button button = new Button();
public Main() throws SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException
{
init();
}
public void click()
{
System.out.println("Button clicked!");
}
public void click2()
{
System.out.println("Button clicked222222!");
}
public void init() throws SecurityException,
NoSuchMethodException, IllegalArgumentException,
IllegalAccessException, InvocationTargetException
{
//做个简单代理
OnClickListenerHandler h = new OnClickListenerHandler(this);
Method method = Main.class.getMethod("click", null);
h.addMethod("onClick", method);
method = Main.class.getMethod("click2", null);
h.addMethod("onClick2", method);
Object clickProxy = Proxy.newProxyInstance(
OnClickListener.class.getClassLoader(),
new Class<?>[] { OnClickListener.class }, h);
Method clickMethod = button.getClass().getMethod("setOnClickLisntener",
OnClickListener.class);
clickMethod.invoke(button, clickProxy);
}
public static void main(String[] args) throws SecurityException,
IllegalArgumentException, NoSuchMethodException,
IllegalAccessException, InvocationTargetException
{
Main main = new Main();
main.button.click();
main.button.click2();
}
}
OnClickListenerHandler类:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class OnClickListenerHandler implements InvocationHandler
{
private Object targetObject;
public OnClickListenerHandler(Object object)
{
this.targetObject = object;
}
private Map<String, Method> methods = new HashMap<String, Method>();
public void addMethod(String methodName, Method method)
{
methods.put(methodName, method);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable
{
String methodName = method.getName();
Method realMethod = methods.get(methodName);
return realMethod.invoke(targetObject, args);
}
}
OnClickListener:接口
public interface OnClickListener {
void onClick();
void onClick2();
}
button类:
public class Button {
private OnClickListener listener;
public void setOnClickLisntener(OnClickListener listener)
{
this.listener = listener;
}
public void click()
{
if (listener != null)
{
listener.onClick();
}
}
public void click2()
{
if (listener != null)
{
listener.onClick2();
}
}
}