Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it allowed to select a static class from a parameterized type in Java?

Here's a minimal demo:

public class OuterStaticNestedDemo<E> {
    class Outer {
        static class StaticNested {}
    }

    void qualifiedNew(Outer outer) {
        new Outer.StaticNested();
        new OuterStaticNestedDemo.Outer.StaticNested();
    }
}

When I compile with javac, it raises an error (using version 25 here, but it's the same for versions 11, 17 and 21) :

javac -g -source 25 -target 25 OuterStaticNestedDemo.java
OuterStaticNestedDemo.java:8: error: cannot select a static class from a parameterized type
        new Outer.StaticNested();
                 ^
1 error

When I compile with ecj, it compiles :

java -jar ecj-3.44.0.jar -g -source 25 -target 25 OuterStaticNestedDemo.java

Is it allowed to select a static class from a parameterized type in Java ?
ecj seems more lenient than javac, or could this be a bug in either of the 2 compilers ?

like image 958
Nicolas Baumann Avatar asked Jun 28 '26 20:06

Nicolas Baumann


1 Answers

No. It is not allowed to select a static class from parameterized type in Java.

This is covered by JLS(Java Language Specification) - 6.5.5.1 (Type Name) and 4.8 (Raw Types).

Key rule:

You may not select a static member from a parameterized type.
Static members must be accessed using a non-parameterized type name.

That rule exists because static members are not associated with any particular instantiation of a generic type.

Inside OuterStaticNestedDemo<E> , Outer class is implicitly parameterized. So new Outer.StaticNested is treated as selecting a static member from parameterized type which is forbidden by JLS.

Fix:

new OuterStaticNestedDemo.Outer.StaticNested();

OuterStaticNestedDemo is a type name; not parameterized type as highlighted by the JLS.

Important rule (JLS - 6.5, 4.5):

A generic class name does not become parameterized unless type arguments are supplied.

So calling OuterStaticNestedDemo.Outer becomes a plain member type. So static class can be selected from this plain context - OuterStaticNestedDemo.Outer.StaticNested

Is ECJ more lenient than java?

Yes, this is certainly a bug from ECJ side. javac will be better to check language correctness in my opinion.

like image 50
Gomathy Jeyam Avatar answered Jul 01 '26 09:07

Gomathy Jeyam



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!