1.创建一个library,butterKnifelibrary
ButterKnife类写主要逻辑
public class ButterKnife { public static void bind(final Activity activity){ Class<Activity> aClass = (Class<Activity>) activity.getClass(); Field[] declaredFields = aClass.getDeclaredFields(); for (Field field:declaredFields) { field.setAccessible(true); if (field.isAnnotationPresent(BindView.class)){ BindView annotation = field.getAnnotation(BindView.class); int id = annotation.value(); View viewById = activity.findViewById(id); try { field.set(activity,viewById); } catch (IllegalAccessException e) { e.printStackTrace(); } } } Method[] declaredMethods = aClass.getDeclaredMethods(); for (final Method method:declaredMethods) { method.setAccessible(true); if (method.isAnnotationPresent(onClick.class)){ onClick annotation = method.getAnnotation(onClick.class); int[] values = annotation.value(); for (int id:values) { final View viewById = activity.findViewById(id); viewById.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { try { method.invoke(activity,viewById); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } }); } } } } }