I was recently working on some Android code (this should be a generic Java question - pardon the pun - about generics and Java auto resolving the type).
Here is my code (Android-based, but please create a java specific version if you need to)
class ViewFinder<T extends View> {
@SuppressWarnings("unchecked")
final static <T> T byId(View view, int resource) {
return (T) view.findViewById(resource);
}
}
Here is the interesting bit...
// Convert XML UI component definitions into the static View Holder object
// Here is what we normally have to do for Android to convert the XML into a UI component
holder.txtGroupName = (TextView) row.findViewById(R.id.txtGroupName);
// This is what I can do with my ViewFinder class above!
holder.txtGroupName = ViewFinder.byId(row, R.id.txtGroupName);
// This is what I was EXPECTING to do with my ViewFinder class above!
holder.txtGroupName = ViewFinder<TextView>.byId(row, R.id.txtGroupName);
No I know that Java (not Android) is resolving the Generic T type to be a TextView UI component, but why and *how*?
Can I get a "play-by-play" of what is going on here? I want to be able to figure out if this is going to happen before I code something next time.
Copyright Notice:Content Author:「Christopher Rucinski」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/19021095/java-android-auto-resolving-generic-type-asking-for-step-by-step-guidance-to