我该怎么写这个代码在
java?
- public class ComponentsManager
- {
- private List<IComponent> list = new ArrayList<IComponent>();
- public <U extends IComponent> U GetComponent() {
- for (IComponent component : list) {
- if(component instanceof U)
- {
- return component;
- }
- }
- }
- }
但是我不能对通用类型执行instanceof.我该怎么办?
谢谢.
解决方法
基本上你不能这样做,因为类型擦除.正常的解决方法是将Class对象作为参数传递;例如
- public <U extends IComponent> U GetComponent(Class<U> clazz) {
- for (IComponent component : list) {
- if (clazz.isInstance(component)) {
- return clazz.cast(component);
- }
- }
- }
你也可以使用if(clazz.equals(component.getClass())){…但是确实类型匹配…这不是instanceof操作符所做的. instanceof运算符和Class.instanceOf方法都会测试该值的类型是否与赋值兼容.