@Retention定义了该Annotation被保留的时间长短:某些Annotation仅出现在源代码中,而被编译器丢弃;而另一些却被编译在class文件中;编译在class文件中的Annotation可能会被虚拟机忽略,而另一些在class被装载时将被读取(请注意并不影响class的执行,因为Annotation与class在使用上是被分离的)。
2.注解事件处理器
编写注解事件处理器,通过反射获得场景类对象的annotation的source对象。并且为source对象调用setOnClickListener方法进行事件绑定。
第二步:对对象进行事件绑定,添加监听事件
import android.view.View;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ActionListenerInstaller {
public static void processAnnotations(Object client) {
Class<?> client = client.getClass();
for (Method m : client.getDeclaredMethods()) {
//获取指定Annotation对象
ActionListener listener = m.getAnnotation(ActionListener.class);