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:

public abstract class CallbackFragment<C> extends Fragment {

    protected C mCallback;
    protected Class<C> callbackClass;

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

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        //just in case
        if(context == null)
            throw new NullPointerException();

        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 = new CallbackFragment<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:

public abstract class CallbackFragment<C> extends Fragment {
    protected Class<C> callbackClass;

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

public class CallbackFragmentOfSomething 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()"