【发布时间】:2013-09-24 01:08:57
【问题描述】:
我想从列表中返回类的对象(作为参数传递给方法)。同样,在返回时,我需要将对象转换为作为参数传递的类。我的问题是我尝试按照下面给出的方式进行操作,但它不正确,因为它给了我编译器错误“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;
}
【问题讨论】:
-
我想返回匹配给定类的“当前”对象
-
此外,“classToFind”是对 Class 对象的引用,但它本身不是类型 - 因此您不能在通常的强制转换语法中使用它。您需要执行类似 classToFind.cast(currentClass) 的操作。见this answer
-
我刚刚注意到:
current将始终是JAXBElement类型。如果您想在运行时检查类型参数,您可能必须使用反射。如果有可能的话。必须通过这个。
标签: java