<分区>
场景:
- 我有一个 Component 类型的私有(private)列表(其中 Component 是一个 抽象类)
- 这个列表有任意数量的不同组件子类 (其中每个派生类型在该列表中都是唯一的)
- 我想提供一种方法,让用户可以找到 他们偏好的特定组件
我的尝试:
private ArrayList<Component> components = new ArrayList<Component>();
public <T extends Component> T getComponent( T type )
{
for ( Component c : components )
{
if ( c instanceof T )
{
return (T) c;
}
}
return null;
}
编译器在 if 语句中报告以下错误:
Cannot perform instanceof check against type parameter T. Use its erasure Component instead since further generic type information will be erased at runtime
实现此行为的推荐方法是什么?