Weird Generics Behavior

· Java

I've stumbled upon this thread and tried it out, just for fun. My intention was to disassemble the resulting classes and see what type the generics uses, and hope that it would product some answer. I changed the original code of ColoredDimension as the thread suggested so it would compile, so that it is now:

class ColoredDimension<T extends Dimension & HasColor> { T item; ColoredDimension(T item) { this.item = item; } T getItem() { return item; } java.awt.Color f() { return item.getColor(); } //int getX() { return item.x; } }

Note the usage of the & operator, which is probably the reason for the mess. Unfortunately, this was the result of javap -c ColoredDimension:

class code.ColoredDimension extends java.lang.Object{
code.Dimension item;

code.ColoredDimension(code.Dimension);
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   aload_0
   5:   aload_1
   6:   putfield        #2; //Field item:Lcode/Dimension;
   9:   return

code.Dimension getItem();
  Code:
   0:   aload_0
   1:   getfield        #2; //Field item:Lcode/Dimension;
   4:   areturn

java.awt.Color f();
  Code:
   0:   aload_0
   1:   getfield        #2; //Field item:Lcode/Dimension;
   4:   checkcast       #3; //class code/HasColor
   7:   invokeinterface #4,  1; //InterfaceMethod code/HasColor.getColor:()Ljava/awt/Color;
   12:  areturn

}
We can see that:
  • The erasure determined item to be of class Dimension.
  • Whenever HasColor is used, it is cast to it, as expected.
  • The ColoredDimension class is located under the code package.
The compiler compiles the class as expected. So obviously it's not the & operator which confuses the compiler, but something in the packages. Why wouldn't it allow access to Dimesion.x? Apparently, it works fine on Eclipse's JDT.