3

I work in Android project and I currently need to create holders for all views. There currently are a lot of if's and I want to get rid of them. Assume there are holders for all views

 if (v instanceof Spinner)
    {
        holder = new SpinnerHolder(v);
    }
    else if (v instanceof AdapterView)
    {
        holder = new AdapterViewHolder((AdapterView) v);
    }
    else if (v instanceof CompoundButton)
    {
        holder = new CompoundButtonHolder(v);
    }
    else if (v instanceof EditText)
    {
        holder = new TextViewHolder(v);
    }
    else if (v instanceof SeekBar)
    {
        holder = new SeekBarHolder(v);
    }
    else if (v instanceof TabHost)
    {
        holder = new TabHostHolder(v);
    }

I sure could do something like

String simpleName = v.getClass().getSimpleName();
Class.forName("com.myproject.myholderpackage" + simpleName + "Holder");
...

But it doesn't work, if, for example, there are custom views like

public class foo extends LinearLayout
{
}
public class bar extends foo
{
}

Thanks.

Heisenberg
  • 3,153
  • 3
  • 27
  • 55

1 Answers1

4

I'd create a map: Map<Class,Class> instanceToHolder and then replace that else-if construction with a single call to that map and some reflection code to run the constructor. So, something like this:

final Map<Class,Class> instanceToHolder = new HashMap<Class,Class>();
instanceToHolder.put(Spinner.class, SpinnerHolder.class);
// ....
Class holderClass = instanceToHolder.get(v.getClass());
Object holderObject = holderClass.getConstructor(v.getClass()).newInstance(v);
ZeroOne
  • 3,041
  • 3
  • 31
  • 52