PhysicsPrincess
PhysicsPrincess

Reputation: 372

Using Java Generics without a type - Generic erasure?

Take a look at this method:

public class Outer<E> {
    public static class Inner{
        public E value;
        public Inner(E value){
            this.value = value;
        }
     }
}

We'll use it using this code:

Outer.Inner i = new Outer.Inner(5);
System.out.println(i.value);

This thing won't compile becuase E is used in the inner method.

My question is - I know that at compile time all the generics are erased and replaced by Object. So why isn't this the case here? E would be replaced by Object and this whole thing should compile.

Does this mean that we can never use Generic classes without the type? (I know that this is bad practice, but I assumed that this should work)

Thanks.

Upvotes: 3

Views: 107

Answers (1)

Sweeper
Sweeper

Reputation: 271410

This has nothing to do with type erasure. This is simply because you can't use type parameters in any static declarations. As the Java Language Specification says:

It is a compile-time error to refer to a type parameter of a generic class C in any of the following:

  • the declaration of a static member of C (§8.3.1.1, §8.4.3.2, §8.5.1).

  • the declaration of a static member of any type declaration nested within C.

  • a static initializer of C (§8.7), or

  • a static initializer of any class declaration nested within C.

The first point applies here.

So not even this will compile:

class Foo<T> {
    public static void f(T param) {}
}

Upvotes: 4

Related Questions