I tried to define a class that wraps android.view.View
and its subclasses, and contains some info on rendering (people might call it as View Model or PresentationModel).
public class MyClass<T extends View>
{
private T view;
private Blah blah;
}
My primal question is if I should make the type of the view variable parameterized or not. Java's Generic implementation seems to be rather simple (e.g. all the type parameter info is erased at compile time), and I can find two possible merits here.
1) Downcasting looks, say, cooler, even if I still have to specify the type somewhere in my codes.
@SuppressWarnings("unchecked")
public final <U extends View> U getView()
{
return (U) view;
}
With above,
Button btn = (Button) obj.getView();
((LinearLayout) obj).addView(view);
becomes
Button btn = obj.getView();
obj.<LinearLayout>addView(view);
2) I may be able to write some polymorphic codes;
@Override
public void bringToFront()
{
// stuff
}
If a method were redefined by some subclasses,
public final T getView()
{
return view;
}
with above,
obj.bringToFront();
might behaves differently depending on the type parameter we gave. The biggest problem is I don't know if there is any actual override case in Google's android framework.
Currently, I'd avoid using Generics, since apparently I can't use HashMap
with the generic class.
Map<String, MyClass<View>> objs = new HashMap<String, MyClass<View>>();
MtClass<Button> obj = objs.get(key); // type mismatch