Skip to content

Instantly share code, notes, and snippets.

@jrobinson3k1
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrobinson3k1/b2efa8d19238655c966b to your computer and use it in GitHub Desktop.
Save jrobinson3k1/b2efa8d19238655c966b to your computer and use it in GitHub Desktop.
Inject an Interface field implemented by an Activity
public static void injectCallbacks(Fragment fragment) {
injectCallbacks(fragment, fragment.getActivity());
}
public static void injectCallbacks(Object obj, Activity activity) {
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(InjectCallback.class)) {
try {
field.setAccessible(true);
field.set(obj, activity);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (IllegalArgumentException e) {
throw new ClassCastException(activity.getClass().getSimpleName() + " must implement " + field.getType().getSimpleName());
}
}
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface InjectCallback {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment