Last active
August 29, 2015 14:02
-
-
Save jrobinson3k1/b2efa8d19238655c966b to your computer and use it in GitHub Desktop.
Inject an Interface field implemented by an Activity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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