avatar

目录
动态代理+注解+反射实现View的点击事件绑定

个人博客

http://www.milovetingting.cn

动态代理+注解+反射实现View的点击事件绑定

代理模式是给对象提供一个代理对象,由代理对象来控制原对象的引用。代理模式分为静态代理和动态代理。

静态代理

定义接口

java
1
2
3
4
5
public interface Player {

void play();

}

定义具体的实现类

java
1
2
3
4
5
6
7
public class PlayerImpl implements Player {

@Override
public void play() {
System.out.println("PlayerImpl play...");
}
}

定义代理类

java
1
2
3
4
5
6
7
8
9
10
11
12
13
public class ProxyImpl implements Player {

private Player player;

public ProxyImpl(Player player) {
this.player = player;
}

@Override
public void play() {
player.play();
}
}

可以看到,具体的实现类和代理类都会实现相同的接口类,在代理类的实现中,会引用具体的实现类。

动态代理

静态代理,在运行前就已经定义。动态代理是在运行时动态创建代理和实例。JDK提供了Proxy类来创建动态代理

java
1
2
3
public static Object newProxyInstance(ClassLoader loader,Class<?>[] interfaces,InvocationHandler h)throws IllegalArgumentException{

}

先看下具体的使用

java
1
2
3
4
5
6
Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{Player.class}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(player, args);
}
});

newProxyInstance对应的三个参数:

  • 类加载器

  • 接口的class,Proxy会根据这个class来生成Proxy类

  • InvocationHandler,方法的回调,被代理类的方法调用时都会回调到这里

动态代理类的完整代码

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class DynamicProxy {

private Player player;

public DynamicProxy(Player player) {
this.player = player;
}

public void setPlayer(Player player) {
this.player = player;
}

public Player getProxy() {
return (Player) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{Player.class}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(player, args);
}
});
}

}

Proxy.newProxyInstance方法最终是调用ProxyGenerator

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public static byte[] generateProxyClass(final String var0, Class<?>[] var1, int var2) {
ProxyGenerator var3 = new ProxyGenerator(var0, var1, var2);
final byte[] var4 = var3.generateClassFile();
if (saveGeneratedFiles) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
try {
int var1 = var0.lastIndexOf(46);
Path var2;
if (var1 > 0) {
Path var3 = Paths.get(var0.substring(0, var1).replace('.', File.separatorChar));
Files.createDirectories(var3);
var2 = var3.resolve(var0.substring(var1 + 1, var0.length()) + ".class");
} else {
var2 = Paths.get(var0 + ".class");
}

Files.write(var2, var4, new OpenOption[0]);
return null;
} catch (IOException var4x) {
throw new InternalError("I/O exception saving generated file: " + var4x);
}
}
});
}

return var4;
}

动态代理生成的代理类存在于内存中。

实现点击事件的绑定

下面基于动态代理+注解+反射,实现控件的点击事件绑定。

首先定义事件类型的注解

java
1
2
3
4
5
6
7
8
@Target(ElementType.ANNOTATION_TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface EventType {

Class listenerType();

String listenerSetter();
}

然后分别定义点击事件和长按事件的注解

java
1
2
3
4
5
6
@EventType(listenerType = View.OnClickListener.class,listenerSetter = "setOnClickListener")
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface OnClick {
@IdRes int[] value();
}
java
1
2
3
4
5
6
@EventType(listenerType = View.OnLongClickListener.class, listenerSetter = "setOnLongClickListener")
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface OnLongClick {
@IdRes int[] value();
}

然后在Activity中定义点击事件

java
1
2
3
4
5
6
7
8
9
10
@OnClick({R.id.btn1, R.id.btn2})
public void click(Button view) {
Toast.makeText(getApplicationContext(), view.getText(), Toast.LENGTH_SHORT).show();
}

@OnLongClick({R.id.btn1, R.id.btn2})
public boolean longClick(Button view) {
Toast.makeText(getApplicationContext(), view.getText() + "-LongClick", Toast.LENGTH_SHORT).show();
return true;
}

在Activity中绑定

java
1
2
3
4
5
6
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
InjectHelper.inject(this);
}

InjectHelper的实现

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
public class InjectHelper {

public static void inject(final Activity target) {
if (target == null) {
return;
}
Class<? extends Activity> clz = target.getClass();
Method[] declaredMethods = clz.getDeclaredMethods();
for (Method method : declaredMethods) {
Annotation[] annotations = method.getAnnotations();
for (Annotation annotation : annotations) {
Class<? extends Annotation> annotationType = annotation.annotationType();
if (annotationType.isAnnotationPresent(EventType.class)) {
EventType eventType = annotationType.getAnnotation(EventType.class);
Class listenerType = eventType.listenerType();
String listenerSetter = eventType.listenerSetter();
try {
Method valueMethod = annotationType.getDeclaredMethod("value");
int[] ids = (int[]) valueMethod.invoke(annotation);
method.setAccessible(true);
ListenerInvocationHandler invocationHandler = new ListenerInvocationHandler(method, target);
Object proxyInstance = Proxy.newProxyInstance(target.getClassLoader(), new Class[]{listenerType}, invocationHandler);
for (int id : ids) {
View view = target.findViewById(id);
Method setter = view.getClass().getMethod(listenerSetter, listenerType);
setter.invoke(view, proxyInstance);
}
} catch (Exception e) {

}
}
}
}
}

static class ListenerInvocationHandler<T> implements InvocationHandler {

private Method method;

private T target;

public ListenerInvocationHandler(Method method, T target) {
this.method = method;
this.target = target;
}

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return this.method.invoke(target, args);
}
}

}
文章作者: milovetingting
文章链接: http://www.milovetingting.cn/2020/04/29/Android/%E5%8A%A8%E6%80%81%E4%BB%A3%E7%90%86+%E6%B3%A8%E8%A7%A3+%E5%8F%8D%E5%B0%84%E5%AE%9E%E7%8E%B0View%E7%9A%84%E7%82%B9%E5%87%BB%E4%BA%8B%E4%BB%B6%E7%BB%91%E5%AE%9A/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 milovetingting

评论