Skip to content

Instantly share code, notes, and snippets.

@hector6872
Last active November 29, 2024 12:06
Show Gist options
  • Save hector6872/9654271c11c0f3c742a58355dc635f11 to your computer and use it in GitHub Desktop.
Save hector6872/9654271c11c0f3c742a58355dc635f11 to your computer and use it in GitHub Desktop.
DRMVPAppCompatActivity example for DaRealMVP library - https://github.com/hector6872/DaRealMVP
@SuppressWarnings("unchecked") public abstract class DRMVPAppCompatActivity<P extends DRMVPPresenter<V>, V extends DRMVPView>
extends AppCompatActivity {
private P presenter;
@CallSuper @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutResId());
presenter = MVPUtils.getDeclaredPresenter(getClass());
presenter.bind((V) this);
}
@CallSuper @Override protected void onDestroy() {
super.onDestroy();
presenter.unbind();
}
protected @NonNull P getPresenter() {
return presenter;
}
protected abstract @LayoutRes int getLayoutResId();
}
public class DRMVPUtils {
@SuppressWarnings("unchecked") public static <P> P getDeclaredPresenter(@NonNull Class clazz) {
Type genericSuperclass;
for (; ; ) {
genericSuperclass = clazz.getGenericSuperclass();
if (genericSuperclass instanceof ParameterizedType) {
break;
}
clazz = clazz.getSuperclass();
}
Type presenterClass = ((ParameterizedType) genericSuperclass).getActualTypeArguments()[0];
try {
return (P) Class.forName(presenterClass.toString().split(" ")[1]).newInstance();
} catch (java.lang.InstantiationException | IllegalAccessException | ClassNotFoundException e) {
throw new IllegalArgumentException();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment