Skip to content

Instantly share code, notes, and snippets.

@Nkzn
Last active May 12, 2016 01:10
Show Gist options
  • Select an option

  • Save Nkzn/9eac047e88624887dfde44f36ef8cd7f to your computer and use it in GitHub Desktop.

Select an option

Save Nkzn/9eac047e88624887dfde44f36ef8cd7f to your computer and use it in GitHub Desktop.
新人さんにButterKnifeを説明するために、bindの偽実装を擬似コードでそれっぽく書いたやつです。APTではなくReflectionで書いてしまったので、 https://github.com/eaglesakura/margarineknife/ に近い発想の実装になった。
class FakeButterKnife {
public static void bind(Activity activity) {
Class class = activity.getClass();
/*
* メンバ変数に付けたBindViewアノテーションを解決する
*/
Field[] fields = class.getDeclaredFields();
for(Field field: fields) {
BindView annotation = field.getAnnotation(BindView.class);
int viewId = annotation.value();
field.set(activity, activity.findViewById(viewId));
}
/*
* メソッドに付けたOnClickアノテーションを解決する
*/
Method[] methods = class.getDeclaredMethods();
for(Method method: methods) {
OnClick annotation = field.getAnnotation(OnClick.class);
int viewId = annotation.value();
View view = activity.findViewById(viewId);
view.setOnClickListener(v -> {
method.invoke(activity);
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment