Let’s say I have the following class:
public class Test<E> { public boolean sameClassAs(Object o) { // TODO help! } }
How would I check that o is the same class as E?
Test<String> test = new Test<String>(); 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
Testhas no information as to whatEis at runtime. So, you need to pass aClass<E>to the constructor of Test.If you want an ‘instanceof’ relationship, use
Class.isAssignableFrominstead of theClasscomparison. Note,Ewill need to be a non-generic type, for the same reasonTestneeds theClassobject.For examples in the Java API, see
java.util.Collections.checkedSetand similar.