views:

92

answers:

1

Why can't I reference the type parameter of a generic parent class inside of contained local classes?

public class IsGeneric<T> {
    public void doSomething(T arg) {
        class A {
            T x;
        }

        A foo = new A();
        foo.x = arg;
        T bar = foo.x;  // error: found java.lang.Object, required T
    }
}

According to Eclipse the above code is perfectly fine, yet javac 1.6.0_11 seems to think that foo.x is of type java.lang.Object. A workaround to the problem is obviously to make A generic itself such as in the following code:

public class IsGeneric<T> {
    public void doSomething(T arg) {
        class A<S> {
            S x;
        }

        A<T> foo = new A<T>();
        foo.x = arg;
        T bar = foo.x;
    }
}

However, I would like to understand what's wrong with the first variant. Any ideas?

+1  A: 

This may be a bug in Sun's javac, see this question which includes possible solutions in the answers.

Vinay Sajip
Thanks for the hint! It turned out to be a known bug of javac: http://bugs.sun.com/view_bug.do?bug_id=6657499
janko