[ACCEPTED]-Java Generics: Comparing the class of Object o to <E>-generics
An instance of Test
has no information as to 7 what E
is at runtime. So, you need to pass 6 a Class<E>
to the constructor of Test.
public class Test<E> {
private final Class<E> clazz;
public Test(Class<E> clazz) {
if (clazz == null) {
throw new NullPointerException();
}
this.clazz = clazz;
}
// To make things easier on clients:
public static <T> Test<T> create(Class<T> clazz) {
return new Test<T>(clazz);
}
public boolean sameClassAs(Object o) {
return o != null && o.getClass() == clazz;
}
}
If you want 5 an "instanceof" relationship, use Class.isAssignableFrom
instead 4 of the Class
comparison. Note, E
will need to 3 be a non-generic type, for the same reason 2 Test
needs the Class
object.
For examples in the Java 1 API, see java.util.Collections.checkedSet
and similar.
The method I've always used is below. It 5 is a pain and a bit ugly, but I haven't 4 found a better one. You have to pass the 3 class type through on construction, as when 2 Generics are compiled class information 1 is lost.
public class Test<E> {
private Class<E> clazz;
public Test(Class<E> clazz) {
this.clazz = clazz;
}
public boolean sameClassAs(Object o) {
return this.clazz.isInstance(o);
}
}
I could only make it working like this:
public class Test<E> {
private E e;
public void setE(E e) {
this.e = e;
}
public boolean sameClassAs(Object o) {
return (o.getClass().equals(e.getClass()));
}
public boolean sameClassAs2(Object o) {
return e.getClass().isInstance(o);
}
}
0
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.