samedi 29 avril 2017

Using reflection and polymorphism with ViewHolder

I have a json with class name, something like this:

{
   "view_class" : "com.view.MyClass"
}

And I have this hierarchy:

    public class Config {
         public String viewClass;
         ...
    }

    public interface ViewHolderInterface {
         void bindValue(...);
    }

    public class SuperMyClass extends RecyclerView.ViewHolder 
implements ViewHolderInterface {
       ... 
    }

    public class MyClass extends SuperMyClass {
       ... 
    }

I read a json file and I generate a "Config" object, so the idea is this:

public void bindViewHolder(SuperMyClass holder, Config config) {

    Class viewHolderClass;

    try {
        //row.viewHolderClass = "com.view.MyClass"
        viewHolderClass = Class.forName(config.viewClass);

    } catch (final Exception exception) {

    }
    // Here I need to "cast" a holder to MyClass and execute the method bindValue.
    final ViewHolderInterface viewHolderInstance =
        (ViewHolderInterface) viewHolderClass.cast(holder);
    viewHolderInstance.bindObjectValue(...);
}

I have tried to do this cast using reflection but I this throws an exception:

java.lang.ClassCastException: SuperMyClass cannot be cast to MyClass

I think that my error is using reflection and the same time try to up-cast, but I have not found another way to do this.

Any idea?





Aucun commentaire:

Enregistrer un commentaire