【问题标题】:How to find and return an object of <derived type> in a list of <base type>? [duplicate]如何在 <base type> 列表中查找并返回 <derived type> 的对象? [复制]
【发布时间】: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


【解决方案1】:

您可能希望依赖Class.isInstanceOf(Object)

for (Component c : components) {
     if (type.getClass().isInstance(c)) {
         return (T) c;
     }
}

确定指定的对象是否与该类表示的对象分配兼容。此方法是 Java 语言 instanceof 运算符的动态等效方法。

提供Class 实例而不是对象会更有意义:

public <T extends Component> T getComponent(Class<T> type)
{
    for (Component c : components) {
         if (type.isInstance(c)) {
             return (T) c;
         }
    }
    return null;
}

【讨论】:

  • Type 应该是Class&lt;T&gt; subclass
  • @LuiggiMendoza 确实更有意义。
  • 这正是我想要的,非常感谢。在我最初的问题中,我可能对此并不完全清楚,但我 试图传入一个类类型作为参数(不是所述类的实例),这就是您的解决方案所完成的。再次感谢。
【解决方案2】:

编译器很清楚

改用它的擦除组件

您可以将参数T type替换为Component c

之后你只需要提取 c 的类型(它将是一个实现,因此 c.getClass() 将是一个扩展 Component 的类)。

你应该检查类型是否匹配并返回第一个元素。

private ArrayList<Component> components = new ArrayList<Component>();

public <T extends Component> T getComponent( Component component )
{
    for ( Component c : components )
    {
        if ( c.getClass().equals(component.getClass()) )
        {
            return c;
        }
    }
    return null;
}

我认为它应该很好用。

希望对你有帮助

【讨论】:

  • 你为什么认为应该很好用
最近更新 更多