DCTest.java(Singleton类)
package com.saphiric.simproject.datacontrols;
/**
* Created by Saphiric on 12/30/14.
*/
public class DCTest {
// Singleton Test
private static DCTest dct = new DCTest();
private DCTest(){
// Prevents outside instantiation
}
public static DCTest getInstance(){
return dct;
}
// test variables for making sure it can have dynamic fields
private int INT;
protected void setInt(int newInt){
INT = newInt;
}
protected int getINT(){
return INT;
}
}
DataCore.java(我想访问Singleton类的文件)
package com.saphiric.simproject.datacontrols;
/**
* Created by Saphiric on 12/29/14.
*/
public class DataCore {
// Singletons Tests
DCTest test = DCTest.getInstance();
test.setInt(0);
public DataController data = new DataController();
public DecisionLocks locks = new DecisionLocks();
}
答案 0 :(得分:1)
您的问题是Java中的方法调用必须在方法中。所以你所拥有的问题实际上与Singleton模式几乎没有关系,那就是你试图在类的主体中进行调用,而不是方法。如果您尝试编译以下内容,则会出现相同的错误:
public class HelloWorld{
System.out.println("Hello, World!"); //Err
}
问题的解决方案取决于您要完成的任务。
如果您尝试在DataCore类的类加载时调用setInt(0)
(并且test
应该是静态字段),请使用静态初始化程序(只是单词{{ 1}}而不是方法标题)。
static
或者,如果字段public class DataCore {
// Singletons Tests - static
static DCTest test;
//Called when the DataCore class is loaded.
static{
test = DCTest.getInstance();
test.setInt(0);
}
}
实际上应该是非静态的,只需将setInt调用放在构造函数中:
test
答案 1 :(得分:-1)
将DataCore
类的代码包含在方法中。
public class DataCore {
// Singletons Tests
public void work () { // added code in this method.
DCTest test = DCTest.getInstance();
test.setInt(0);
public DataController data = new DataController();
public DecisionLocks locks = new DecisionLocks();
}
}