Java instanceof workaround … here is a solution to the problem.
Java instanceof workaround
I’m working on an Android project and currently need to create containers for all Views. There are a lot of ifs at the moment and I want to get rid of them. Assume that all views have holders
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 can certainly do something similar
String simpleName = v.getClass().getSimpleName();
Class.forName("com.myproject.myholderpackage" + simpleName + "Holder");
...
But it doesn’t work, for example, if there is a custom View like this
public class foo extends LinearLayout
{
}
public class bar extends foo
{
}
Thank you.