Java – how to compare the instance type of an object with a generic type?

How do I write this code in 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;
                }
            }
        }
}

But I can't execute instanceof. On generic types What should I do? thank you.

Solution

Basically you can't do this because of type erasure The normal solution is to pass the class object as a parameter; for example

public <U extends IComponent> U GetComponent(Class<U> clazz) {
        for (IComponent component : list) {
            if (clazz.isinstance(component)) {
                return clazz.cast(component);
            }
        }
    }

You can also use if (clazz. Equals (component. Getclass()) {... But the type does match... This is not done by the instanceof operator. Both the instanceof operator and the class. Instanceof method will test whether the type of the value is compatible with the assignment

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>