Android 注解反射例子

简单的实现onClick注解




    
public class MainActivity extends AppCompatActivity {

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

    @ClickView(R.id.btn_1)
    void onClick() {
        Toast.makeText(this, "hello world", Toast.LENGTH_SHORT).show();
    }
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface ClickView {
    int value();
}


public class ViewAnnoTool {

    public static void init(Activity activity) {
        bindClick(activity);
    }

    private static void bindClick(Activity activity) {
        //1、先获取到当前类
        Class clazz = activity.getClass();
        // 2、获取类中定义的方法
        Method[] methods = clazz.getDeclaredMethods();
        for (int i = 0; i < methods.length; i++) {
            Method method = methods[i];
            // 3、获取到方法的注解
            ClickView clickView = method.getAnnotation(ClickView.class);
            if (clickView != null) {
                // 4、获取到注解的值 也就是view的 id
                int value = clickView.value();
                View view = activity.findViewById(value);
                if(view != null) {
                    view.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            method.setAccessible(true);
                            // 4、在触发onClick的时候调用带注解的方法
                            try {
                                method.invoke(activity, null);
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            } catch (InvocationTargetException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            }
        }
    }
}

效果:


飞书20220714-214006.jpg

你可能感兴趣的:(Android 注解反射例子)