how can 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 cant perform instanceof on generic types. how should i do it? thanks.
Use the IsGenericType property to determine whether the type is generic, and use the IsGenericTypeDefinition property to determine whether the type is a generic type definition. Get an array that contains the generic type arguments, using the GetGenericArguments method.
To enable two objects of a generic type parameter to be compared, they must implement the IComparable or IComparable<T>, and/or IEquatable<T> interfaces. Both versions of IComparable define the CompareTo() method and IEquatable<T> defines the Equals() method.
The actual type arguments of a generic type are. reference types, wildcards, or. parameterized types (i.e. instantiations of other generic types).
A generic type is declared by specifying a type parameter in an angle brackets after a type name, e.g. TypeName<T> where T is a type parameter.
Basically you can't do that due to type erasure. The normal workaround is to pass a Class
object as a parameter; e.g.
public <U extends IComponent> U GetComponent(Class<U> clazz) {
for (IComponent component : list) {
if (clazz.isInstance(component)) {
return clazz.cast(component);
}
}
}
You could also use if (clazz.equals(component.getClass())) { ...
but that does an exact type match ... which is not what the instanceof
operator does. The instanceof
operator and the Class.instanceOf
method both test to see if the value's type is assignment compatible.
You could try adding a couple of 'test' methods:
private static <U extends IComponent> boolean testComponent(U u) {
return true;
}
private static boolean testComponent(Object o) {
return false;
}
Then, use testComponent(component)
instead of component instanceof U
.
Example code:
import java.util.*;
class IComponent {
}
class T1 extends IComponent {
}
public class Test {
public static <U extends IComponent> boolean testComponent(U u) {
return true;
}
public static boolean testComponent(Object o) {
return false;
}
public static void main(String[] args) {
T1 t = new T1();
System.out.println("hm? " + (testComponent(t) ? "true" : "false"));
}
}
Output:
hm? true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With