java - 如何在 <base type> 的列表中查找并返回 <derived type> 的对象?

标签 java generics reflection

<分区>

场景:

  • 我有一个 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

实现此行为的推荐方法是什么?

最佳答案

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

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

Determines if the specified Object is assignment-compatible with the object represented by this Class. This method is the dynamic equivalent of the Java language instanceof operator.

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

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

关于java - 如何在 <base type> 的列表中查找并返回 <derived type> 的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32892939/

相关文章:

java - 仅来 self 的包的 Spring Boot 堆栈跟踪日志记录过滤器

java - 导入新包的类名冲突(java)

typescript ,合并对象类型?

Java 反射(reflect)嵌套的匿名类

java - xml 的正则表达式不起作用

java - 如何在 FragmentPagerAdapter 中的 fragment 之间传递数据

泛型和 Xstream

swift - Swift is Operator 的意外结果

c# - 如何判断一个类是否构造完成(实例构造完成)?

c# - 隐藏类型不在 .net 中的 Assembly.GetTypes 中列出