在 activity 中
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = ((Button) findViewById(R.id.btn1));
//hook 钩,反射和代理的应用
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("qqq==", "33333333333333");
}
});
//hookView(btn1);
hookView1(btn1);
}
//反射+静态代理
private void hookView(View v) {
try {
//获取代理点(代理点是一个对象,优先考虑静态变量和单例)
Class<?> c = Class.forName("android.view.View");
Method method = c.getDeclaredMethod("getListenerInfo");
method.setAccessible(true);
Object obj = method.invoke(v);
//对 代理点的类,进行反射
Class<?> cInfo = Class.forName("android.view.View$ListenerInfo");
Field methodClick = cInfo.getDeclaredField("mOnClickListener");
methodClick.setAccessible(true);
View.OnClickListener clickListener = (View.OnClickListener) methodClick.get(obj);
//修改 代理点的 属性
//methodClick.set(obj, new MyClickListener());
methodClick.set(obj, new MyClickListener(clickListener));
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
private class MyClickListener implements View.OnClickListener {
private View.OnClickListener click;
public MyClickListener() {
}
public MyClickListener(View.OnClickListener click) {
//被 替换掉 的 View.OnClickListener对象
this.click = click;
}
@Override
public void onClick(View v) {
Log.i("qqq==", "2222222222");
if (click != null) click.onClick(v);
}
}
//另一种方式, //反射+动态代理
private void hookView1(View v) {
try {
Class<?> c = Class.forName("android.view.View");
Method method = c.getDeclaredMethod("getListenerInfo");
method.setAccessible(true);
//ListenerInfo 的对象
Object obj = method.invoke(v);
//使用 动态代理模式的方法
Object newProxyInstance = Proxy.newProxyInstance(
View.OnClickListener.class.getClassLoader(),
new Class[]{View.OnClickListener.class},
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method,
Object[] args) throws Throwable {
Log.i("qqq--", "InvocationHandler调用了");
return null;
}
}
);
//修改 代理点的 属性
Class<?> cListenerInfo = Class.forName("android.view.View$ListenerInfo");
Field field = cListenerInfo.getDeclaredField("mOnClickListener");
field.setAccessible(true);
field.set(obj, newProxyInstance);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}