java泛型返回类型的方法应该是传递相同的传递参数

big*_*big 2 java

我想从列表中返回类的对象(作为参数传递给方法).同时返回时我需要将对象强制转换为作为参数传递的类.我的问题是我尝试按照下面给出的但是它不正确,因为它给了我编译器错误"classToFind无法解析为类型"

private <T extends myClass> T findObject(List<JAXBElement<? extends myClass>> list, 
          Class<? extends myClass> classToFind) {
    for (JAXBElement<? extends myClass> current : list) {
        if(current.getClass() == classToFind) {
               return (classToFind) currentClass; // error "classToFind cannot be resolved to a type"
        }
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)

Hol*_*ger 5

return classToFind.cast(current).与其他解决方案不同,这是类型安全的,不需要SuppressWarnings.但是,显然,第二个参数Class<T> classToFind在任何情况下都必须改变.