Cannot `import static` static nested class?

前端 未结 2 1426
情深已故
情深已故 2021-01-12 09:52

I have a class A with a static nested class inside it called B:

import static A.B.*;

class A {
    static class B {
        static         


        
相关标签:
2条回答
  • 2021-01-12 10:31

    This won't work if A is in the default package. However, you could add a package declaration:

    package mypackage;
    

    and use

    import static mypackage.A.B.*;
    

    The static import syntax from from the JLS is given:

    SingleStaticImportDeclaration: import static TypeName . Identifier ;

    where TypeName is required to be full qualified.

    In Using Package Members the static import syntax is given with package name included:

    import static mypackage.MyConstants.*;
    

    It is recommended to use static imports very sparingly.

    0 讨论(0)
  • 2021-01-12 10:31

    It should be

    import <the-package-for-the-class-A>.A.B.*;
    

    If A is in the default package, this will fail.

    Last, it's not a good practice to import *. Just import only the things that you need, in this case - import static <the-package-for-the-class-A>.A.B.x; if you're gonna use only the x variable.

    0 讨论(0)
提交回复
热议问题