The run-time type information operator instanceof: determines if an object is an instance of a class.
The instanceof operator can be applied to objects of generic classes.
class Gen<T> {
T ob;
Gen(T o) {
ob = o;
}
T getObject() {
return ob;
}
}
class Gen2<T> extends Gen<T> {
Gen2(T o) {
super(o);
}
}
public class MainClass {
public static void main(String args[]) {
Gen<Integer> iOb = new Gen<Integer>(88);
Gen2<Integer> iOb2 = new Gen2<Integer>(99);
Gen2<String> strOb2 = new Gen2<String>("Generics Test");
if(iOb2 instanceof Gen2<?>){
System.out.println("iOb2 is instance of Gen2");
}
if(iOb2 instanceof Gen<?>){
System.out.println("iOb2 is instance of Gen");
}
if(strOb2 instanceof Gen2<?>){
System.out.println("strOb is instance of Gen2");
}
if(strOb2 instanceof Gen<?>){
System.out.println("strOb is instance of Gen");
}
if(iOb instanceof Gen2<?>){
System.out.println("iOb is instance of Gen2");
}
if(iOb instanceof Gen<?>){
System.out.println("iOb is instance of Gen");
}
// The following can't be compiled because
// generic type info does not exist at runtime.
// if(iOb2 instanceof Gen2<Integer>)
// System.out.println("iOb2 is instance of Gen2<Integer>");
}
}
iOb2 is instance of Gen2
iOb2 is instance of Gen
strOb is instance of Gen2
strOb is instance of Gen
iOb is instance of Gen