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


    个人博客

    http://www.milovetingting.cn

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

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

    静态代理

    定义接口

    public interface Player {
    
        void play();
    
    }
    

    定义具体的实现类

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

    定义代理类

    public class ProxyImpl implements Player {
    
        private Player player;
    
        public ProxyImpl(Player player) {
            this.player = player;
        }
    
        @Override
        public void play() {
            player.play();
        }
    }
    

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

    动态代理

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

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

    先看下具体的使用

    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,方法的回调,被代理类的方法调用时都会回调到这里

    动态代理类的完整代码

    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

    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;
        }
    

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

    实现点击事件的绑定

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

    首先定义事件类型的注解

    @Target(ElementType.ANNOTATION_TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface EventType {
    
        Class listenerType();
    
        String listenerSetter();
    }
    

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

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

    然后在Activity中定义点击事件

    @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中绑定

    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            InjectHelper.inject(this);
        }
    

    InjectHelper的实现

    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);
            }
        }
    
    }
    
  • 相关阅读:
    【oracle】 DDL,DML,DCL区别
    【python】模块初识之random模块
    【python】模块初识之re模块
    【python】模块初识之time模块
    【python】属性和类方法
    【python】面向对象初识之封装
    【python】面向对象初识之多态
    【python】面向对象初识之继承
    【python】面向对象初识
    【python】二分查找
  • 原文地址:https://www.cnblogs.com/milovetingting/p/12803464.html
Copyright © 2020-2023  润新知