不能`导入静态`静态内部类? [英] Cannot `import static` static inner class?

查看:318
本文介绍了不能`导入静态`静态内部类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类 A ,里面有一个静态内部类,名为 B

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

import static A.B.*;

class A {
    static class B {
        static int x;
        static int y;
    }
    public static void main(String[] args) {
        System.out.println(x);
    }
}

我想静态导入<$ c $中的所有内容c> B ,但它无法工作:

I want to static import everything in B, but it wont work:

$ javac A.java
A.java:1: package A does not exist
import static A.B.*;
               ^
A.java:9: cannot find symbol
symbol  : variable x
location: class A
        System.out.println(x);
                           ^
2 errors

为什么?

推荐答案

如果 A 在默认包中,则无效。但是,您可以添加包声明:

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

package mypackage;

并使用

import static mypackage.A.B.*;

来自 JLS 给出:


SingleStaticImportDeclaration:
import static TypeName 。标识符;

其中 TypeName 必须是完全合格

使用包成员,包含包名称的静态导入语法:

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

import static mypackage.MyConstants.*;

建议使用 static 非常谨慎地导入。

这篇关于不能`导入静态`静态内部类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆