我最近正在研究一些 Android 代码(这应该是一个通用的 Java 问题——请原谅双关语——关于泛型和 Java 自动解析类型)。
这是我的代码(基于 Android,但如果需要,请创建 Java 特定版本)
class ViewFinder<T extends View> {
@SuppressWarnings("unchecked")
final static <T> T byId(View view, int resource) {
return (T) view.findViewById(resource);
}
}
这是有趣的一点……
// 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);
不,我知道 Java(不是 Android)正在将 Generic T 类型解析为 TextView UI 组件,但为什么和 *如何*?
我可以了解这里发生的事情吗?我希望能够在下次编写代码之前弄清楚这是否会发生。