【问题标题】:Unable to import a class statically in Java无法在 Java 中静态导入类
【发布时间】:2018-02-18 01:18:23
【问题描述】:

我有一个 java 文件,其中包含我希望静态导入另一个文件的内容列表。

但是,我遇到了编译器“找不到符号”的错误。

可视化代码也高亮了出现错误的代码:

语法错误,静态导入仅在源级别为 1.5 时可用 或更高。

我遵循了 post 的语法。

常量.java

public final class Constants{
    private Constants(){} //Private constructor - no instantiation or subclassing.

    // The first two members are constants, used to configure the simulator.
    public static final int MAX_NUMBER_OF_EVENTS = 100; // Maximum number of events 
    public static final double SERVICE_TIME = 1.0; // Time spent serving a customer
    public static final int CUSTOMER_ARRIVE = 1;
    public static final int CUSTOMER_DONE = 2;
}

模拟器.java

import static Constants.*; //doesn't work.

public class Simulator{   
    private Event[] events = new Event[MAX_NUMBER_OF_EVENTS]; //Array to queue events - order of events not guaranteed.

    //numOfEvents keeps track of number of events in the array.
    //total* variables used to track simulation.
    //*Id variables used to identify customer.
    private int numOfEvents, totalNumOfServedCustomer, totalNumOfLostCustomer =  0;
    private int lastCustomerId = 0;
    private int servedCustomerId, waitingCustomerId = -1;

    //booleans used to track customer status i.e. served or waiting.
    private boolean customerBeingServed, customerWaiting = false;

    //doubles used to keep track of time of total simulation and waiting time.
    private double timeStartedWaiting, totalWaitingTime = 0;
...
}

我在 JDK 9 上运行带有 Red hat 对 Java 语言支持的 Visual Code。

【问题讨论】:

标签: java static


【解决方案1】:

您不能从默认包中导入。

给你的常量类一个包声明:

package something;

导入使用

import static something.Constants.*;

【讨论】:

    猜你喜欢
    • 2013-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-28
    相关资源
    最近更新 更多