JDK-6481176 : java.lang.reflect breaks java generics
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.lang:reflect
  • Affected Version: 5.0
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • OS: windows_xp
  • CPU: x86
  • Submitted: 2006-10-12
  • Updated: 2012-09-28
  • Resolved: 2006-10-13
Related Reports
Duplicate :  
Description
FULL PRODUCT VERSION :
1.5

A DESCRIPTION OF THE PROBLEM :
You can trick, and in-doing-so break, java generics into accepting invalid class types as method parameters by using java.lang.reflect framework. No exception gets thrown.

STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
execute the attached code

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
an exception to get thrown or some indication that something went wrong
ACTUAL -
no exception and no indication

ERROR MESSAGES/STACK TRACES THAT OCCUR :
would be nice

REPRODUCIBILITY :
This bug can be reproduced always.

---------- BEGIN SOURCE ----------
import java.lang.reflect.*;

class Z {}
class Z1 extends Z {}
class Z2 extends Z{}

class A<T extends Z> {
  T hold;
  public void set(T value) {
    hold = value;
  }
}

class B extends A<Z1> {}
class C extends A<Z2> {}

class Test {
  public static void main(String[] args) throws Exception {
    B type = new B();
    A<?> type_super = (A<?>) type;
    type_super.getClass().getMethod("set", new Class[] { Z.class }).invoke(type_super, new Z2());
    //You are essentally creating an instance of class B, then calling
    // B.set() with parameter of type Z2 even though you can only
    // call B.set() with a parameter of type Z1
    //An exception doesn't get thrown
    //This is a bug!
    System.out.println("This is a bug!");
  }
}
---------- END SOURCE ----------