Let's say I have the following class:
public class Test {
public boolean sameClassAs(Object o) {
// TODO help!
}
}
How would I check that o is the same class as E?
Test test = new Test();
test.sameClassAs("a string"); // returns true;
test.sameClassAs(4); // returns false;
I can't change the method signature from (Object o) as I'm overridding a superclass and so don't get to choose my method signature.
I would also rather not go down the road of attempting a cast and then catching the resulting exception if it fails.
解决方案
An instance of Test has no information as to what E is at runtime. So, you need to pass a Class to the constructor of Test.
public class Test {
private final Class clazz;
public Test(Class clazz) {
if (clazz == null) {
throw new NullPointerException();
}
this.clazz = clazz;
}
// To make things easier on clients:
public static Test create(Class clazz) {
return new Test(clazz);
}
public boolean sameClassAs(Object o) {
return o != null && o.getClass() == clazz;
}
}
If you want an "instanceof" relationship, use Class.isAssignableFrom instead of the Class comparison. Note, E will need to be a non-generic type, for the same reason Test needs the Class object.
For examples in the Java API, see java.util.Collections.checkedSet and similar.