【发布时间】:2026-01-17 08:30:01
【问题描述】:
场景:
- 我有一个 Component 类型的私有列表(其中 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语句上报如下错误:
无法对类型参数 T 执行 instanceof 检查。请改用其擦除组件,因为更多的泛型类型信息将在运行时被擦除
实现此行为的推荐方法是什么?
【问题讨论】:
-
这里真的需要泛型吗?使用 Class 作为 getComponent 参数。像这样 public Component getComponent(Class type) { for ( Component c : components ) { if ( c.getClass().equals(type)) { return c; } } 返回空值; }
标签: java generics reflection