Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Java Generics without a type - Generic erasure?

Tags:

java

generics

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.

like image 624
PhysicsPrincess Avatar asked May 06 '26 07:05

PhysicsPrincess


1 Answers

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) {}
}
like image 59
Sweeper Avatar answered May 08 '26 04:05

Sweeper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!