java.lang.Error:singelton类的未解决的编译问题

时间:2019-08-27 13:15:19

标签: java eclipse compiler-errors

我有一个包含两个声明为singeltone类的类的程序。 当我尝试运行该程序时,出现了java.lang.Error:在获取singeltone类实例的行中出现未解决的编译问题,我不明白为什么。

错误:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 

    at Model.Recommender.getInstance(Recommender.java:22)
    at Model.Library.<clinit>(Library.java:21)
    at Controller.MainClass.main(MainClass.java:69)

推荐类中的错误行:

public static Recommender getInstance() {

该类以这种方式声明:

public class Recommender {

    private static Recommender recommender; //a recommender
    private HashSet<Reader> libraryReaders; //a hash set of all of the library readers

    //constructor to initialize the fields
    private Recommender() 
    {
        libraryReaders = new HashSet<Reader>();
    }

    //method to make the class a singleton class
    public static Recommender getInstance() {
        if(recommender == null) //check that a instance of this class doesn't exist
        {
            recommender = new Recommender(); //creates a new instance
        }
        return recommender; //return the instance that was created
    }
}

库类中的错误行:

private static Recommender recommender = Recommender.getInstance();

该类以这种方式声明:

public class Library {

    private static Library library; //a library
    private static Recommender recommender = Recommender.getInstance();
    private HashSet<Reader> readers;
    private HashSet<Author> authors;
    private HashSet<LibraryItem> items;

    //constructor to initialize the fields
    private Library() {
        readers = new HashSet<Reader>();
        authors = new HashSet<Author>();
        items = new HashSet<LibraryItem>();
    }

    //method to make the class a singleton class
    public static Library getInstance() {
        if(library == null) //check that a instance of this class doesn't exist
        {
            library = new Library(); //creates a new instance
        }
        return library; //return the instance that was created
    }
}

Main类中的错误:

LibrarySys = Library.getInstance();

我正在库类中创建一个荐荐实例,并在主类中创建一个库实例。为什么会出现此错误?

2 个答案:

答案 0 :(得分:0)

什么是LibrarySys? 不应该吧

Library myLibrary = Library.getInstance();

答案 1 :(得分:0)

您发布的代码很好。至于编译错误,则必须检查导入,未用此代码编写的其他类,例如Reader,Author和LibraryItem。您在应用程序中使用外部JAR吗?也许是您的类路径问题。

此外,在2019年,您的Recommender单例类可以简单地作为枚举编写,而无需使用getInstance()方法(无论如何都不是线程安全的),如下所示:

period1_time_out = period2_time_in

}

使用它就像编写Recommender.INSTANCE一样简单,无需初始化任何东西。