Java Generic type info at runtime

Question

What is the output of the following code?


// Use the instanceof operator with a generic class hierarchy.  
class MyClass<T> {
  T ob;/*from   w ww . j  a  va 2 s. c  o  m*/

  MyClass(T o) {
    ob = o;
  }

  // Return ob.
  T getob() {
    return ob;
  }
}

class MySubclass<T> extends MyClass<T> {
  MySubclass(T o) {
    super(o);
  }
}

// Demonstrate run-time type ID implications of generic
// class hierarchy.
public class Main {
  public static void main(String args[]) {

    MyClass<Integer> iOb = new MyClass<Integer>(88);

    MySubclass<Integer> iOb2 = new MySubclass<Integer>(99);

    MySubclass<String> strOb2 = new MySubclass<String>("Generics Test");


    if(iOb2 instanceof MySubclass<Integer>){
      System.out.println("iOb2 is instance of Gen2<Integer>");  
    }
  }
}


Compile time error

Note

The generic type info does not exist at run-time.

The code attempted to compare iOb2 with a specific type of MySubclass.

There is no generic type information available at run time.




PreviousNext

Related