Skip to content Skip to sidebar Skip to footer

How To Check Typed Callback Type Inside Fragment.onattach()

I'm trying to implement abstract fragment with typed callback to use it in several subclasses. How can I check if Context is instance of appropriate class? My code of abstact Callb

Solution 1:

mCallback = (C) context; //this line not seems to throw any exception

this call will never throw an Exception. During Runtime, your C is replaced with Object(that's called Type-Erasure) - and everything is an Object. Therefore you can assign anything at this point.

To have the exception (or at least error-determination) at the point, where you need it, you can use:

publicabstractclassCallbackFragment<C> extendsFragment {

    protected C mCallback;
    protectedClass<C> callbackClass;

    publicCallbackFragment(Class<C> clazz) {
       this.callbackClass = clazz;
    }

    @OverridepublicvoidonAttach(Context context) {
        super.onAttach(context);

        //just in caseif(context == null)
            thrownewNullPointerException();

        if (clazz.isAssignableFrom(context.getClass()){
            mCallback = (C) context;  
        }else{
           //oops
        }
    }
}

ofc. then your FragmentCreation would change from

 CallbackFragment<Something> fragment = new CallbackFragment<Something>();

to

CallbackFragment<Something> fragment = newCallbackFragment<Something>(Something.class);

It's a little different, but allows you to keep track of the actual type at any time, bypassing the Type-Erasure.

ps.: For Inherited classes, you can do it more generic:

publicabstractclassCallbackFragment<C> extendsFragment {
    protected Class<C> callbackClass;

    publicCallbackFragment() {
          this.callbackClass = (Class<C>) ((ParameterizedType) getClass()
                        .getGenericSuperclass()).getActualTypeArguments()[0];;
     }
}

publicclassCallbackFragmentOfSomething extends <CallbackFragment<Something>>{

}

This only fails, if your actual class is not defined due to inheritance, but "on the fly":

CallbackFragment<Something> fragment = new CallbackFragment<Something>();

(Everything untested / no copy paste, but should be somewhat accurate)

Post a Comment for "How To Check Typed Callback Type Inside Fragment.onattach()"