Java 访问在另一个对象中创建的对象

Java 访问在另一个对象中创建的对象,java,design-patterns,scope,singleton,instance,Java,Design Patterns,Scope,Singleton,Instance,我觉得我的问题很简单,但我不知道用谷歌搜索是为了什么 我有一个run.java,它基本上就是这样做的 public class run { //stuff public static void main(String[] args) { //stuff Solver solver = new Solver(body,seeds); solver.solve(); LogTool.print("OUTPUT

我觉得我的问题很简单,但我不知道用谷歌搜索是为了什么

我有一个run.java,它基本上就是这样做的

public class run {
    //stuff
    public static void main(String[] args) {
        //stuff     
        Solver solver = new Solver(body,seeds);
        solver.solve();
        LogTool.print("OUTPUT field of CLASS CREATED IN solver -- " + IDONTKNOWHOW,"notification");
    }
}
===========
public class Solver {
    //stuff
    public void solve() {
        //stuff
        GlobalState GLowestState = new GlobalState(this.Cur_state);
    }
}
那么,如何从run.java中访问GLowestState呢

GLowestState是用单例实现的,这会有区别吗?
我希望不会。
我无法尝试任何操作,因为我的IDE为GLowestState.IDONTKNOWHOW提供了一个错误

==============

更新更多代码:

public class run {
public static void main(String[] args) {

        Voxel [][][] body = new Voxel[Config.xDIM][Config.yDIM][Config.zDIM];
         //stuff

        Solver solver = new Solver(body,seeds);        

        LogTool.print("Initialized Solver Object!","notification");
        LogTool.print("Beginning Annealing...","notification");
        looper.solveSA();
        GlobalState GLS = looper.getGLowestState();  <--- NPE here
        LogTool.print("GLC: " + looper.getGlobal_lowest_cost()+ " CURC: " + looper.getCur_cost(),"notification");
//        LogTool.print("GLS external: " + GLS,"notification");
        LogTool.print("SolveSA: Global Current Best Solution : " + looper.getGlobal_Lowest_state_string(),"notification");

=========
public class Looper {
    public static Voxel [][][] body; //Thobi hat das als ganz einfache Variable in seiner Loesermethode...nicht so OOP
    public static Seed[] seeds = new Seed[Config.SAnumberOfSeeds];
    public double[] Cur_state = new double[Config.SAnumberOfSeeds];
    public double[] New_state = new double[Config.SAnumberOfSeeds]; // Do I even need this ?
    public double[] Global_Lowest_state = new double[Config.SAnumberOfSeeds]; // Do I even need this ?
    GlobalState GLowestState;

    public Looper(Voxel [][][] body, Seed[] seeds) {
        this.temperature = Config.StartTemp;
        this.body = body;
        this.seeds = seeds;
                this.Cur_cost = Cur_cost;
                this.New_cost = New_cost;
                this.temperature = temperature;
                this.Cur_state = Cur_state;
                this.New_state = New_state;
                this.Global_lowest_cost = Double.MAX_VALUE;
                this.Global_Lowest_state = Global_Lowest_state;
    }

    public GlobalState getGLowestState() {
        return GLowestState;
    }



        for (int ab = 0; ab < Config.NumberOfMetropolisResets; ab++) {
            LogTool.print("==================== START CALC FOR OUTER ROUND " + ab + "=========================","notification");

            if (Config.SAverboselvl==1) {
                LogTool.print("SolveSA: Cur_State Read before Metropolis : A)" + Cur_state[0] + " B) " + Cur_state[1] + " C) " + Cur_state[2],"notification");
                LogTool.print("Debug: GLS get 1: " + this.getGlobal_Lowest_state_string(),"notification");
            }

            if (ab==0){
                this.initState();

                if (Config.SAverboselvl==1) {
                    LogTool.print("SolveSA: Cur_state after Initstate : A)" + Cur_state[0] + " B) " + Cur_state[1] + " C) " + Cur_state[2],"notification");
                }
            }

            setCur_cost(cost());

            /* [Newstate] with random dwelltimes */
            newState(); 
            if (Config.SAverboselvl==1) {
                LogTool.print("SolveSA: New State before Metropolis: A)" + New_state[0] + " B) " + New_state[1] + " C) " + New_state[2],"notification");
            }

            setNew_cost(cost());

            if (Config.SAverboselvl==1) {
                LogTool.print("SolveSA: New Cost : " + New_cost,"notification");
            }

            double random_double = RandGenerator.randDouble(0.01, 0.99);

            /**
                * MetropolisLoop
                * @param Config.NumberOfMetropolisRounds
             */

            for(int x=0;x<Config.NumberOfMetropolisRounds;x++) {   
    //            break;
    //            LogTool.print("SolveSA Iteration " + x + " Curcost " + Cur_cost + " Newcost " + New_cost,"notification");
               if ((Cur_cost - New_cost)>0) { // ? die Kosten

                   if (Config.SAverboselvl>1) {
                       LogTool.print("Fall 1","notification");
                   }

                   if (Config.SAdebug) {                      
                          LogTool.print("SolveSA: Metropolis NewCost : " + this.getNew_cost(),"notification");
                          LogTool.print("SolveSA: Metropolis CurCost : " + this.getCur_cost(),"notification");
                          LogTool.print("SolveSA Cost delta " + (Cur_cost - New_cost) + " ","notification");
                   }
                          Cur_state = New_state;
                          Cur_cost = New_cost;

                    } else if (Math.exp(-(Cur_cost - New_cost)/temperature)> random_double) {

                        Cur_state = New_state;
                        Cur_cost = New_cost;

                        if (Config.SAdebug) {
                            LogTool.print("SolveSA: NewCost : " + this.getNew_cost(),"notification");
                            LogTool.print("SolveSA: CurCost : " + this.getCur_cost(),"notification");
                        }

                        if (Config.SAverboselvl>1) {
                            LogTool.print("Fall 2: Zufallsgenerierter Zustand traegt hoehere Kosten als vorhergehender Zustand. Iteration: " + x,"notification");
                        }
                    }

               temperature = temperature-1;
               if (temperature==0)  {
                   break;
               }

               random_double = RandGenerator.randDouble(0.01, 0.99);
               newState();
               setNew_cost(cost());
            }

            if (ab==9) {
                double diff=0;
            }

//This is where the trouble happens - GlobalLoewst cost is set correctly and kept throughout the loops, GLowestState is always the last value of Cur_State (the most recent completed iteration. If smoothly running, that would be iteration 9 and inner iteration 99) @stackexchange

            if (Cur_cost<Global_lowest_cost) {
                this.setGlobal_lowest_cost(Cur_cost);
                GlobalState GLowestState = new GlobalState(this.Cur_state);
                LogTool.print("GLS DEDICATED OBJECT STATE OUTPUT  -- " + GLowestState.getGlobal_Lowest_state_string(),"notification");
                this.setGlobal_Lowest_state(GLowestState.getDwelltimes());
                LogTool.print("READ FROM OBJECT OUTPUT  -- " + this.getGlobal_Lowest_state_string(),"notification");
//                LogTool.print("DEBUG: CurCost direct : " + this.getCur_cost(),"notification");        
//                LogTool.print("Debug: Cur<global CurState get : " + this.getCur_state_string(),"notification");
//                LogTool.print("Debug: Cur<global GLS get : " + this.getGlobal_Lowest_state_string(),"notification");
//                this.setGlobal_Lowest_state(this.getCur_state(Cur_state));
//                LogTool.print("Debug: Cur<global GLS get after set : " + this.getGlobal_Lowest_state_string(),"notification");        
            }
            LogTool.print("SolveSA: Iteration : " + ab,"notification");
            LogTool.print("SolveSA: Last Calculated New State/Possible state inner loop 99 : " + this.getNew_state_string(),"notification");
//            LogTool.print("SolveSA: Best Solution : " + this.getCur_state_string(),"notification");
            LogTool.print("SolveSA: GLS after: " + this.getGlobal_Lowest_state_string(),"notification");
            LogTool.print("SolveSA: NewCost : " + this.getNew_cost(),"notification");
            LogTool.print("SolveSA: CurCost : " + this.getCur_cost(),"notification");        
        }
    }

=================

public final class GlobalState implements Comparable<Object>{
    private double[] dwelltimes;
    private static GlobalState instance = null;

    protected GlobalState(){
        // Exists only to defeat instantiation
    }

    public static GlobalState getInstance(){
        if (instance==null){
            instance = new GlobalState();
        }
        return instance;
    }

    public GlobalState(double[] dwelltimes) {
        this.dwelltimes = dwelltimes;
    }

    @Override
    public int compareTo(Object o) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    public double[] getDwelltimes() {
        return dwelltimes;
    }

    public String getGlobal_Lowest_state_string() {
        String Global_Lowest_state_string = new String();
        for (int cc = 0; cc < Config.SAnumberOfSeeds; cc++) {
            Global_Lowest_state_string = Global_Lowest_state_string.concat(" " + cc + ") " + dwelltimes[cc]);
            }
        return Global_Lowest_state_string;
    }

    public void setDwelltimes(double[] dwelltimes_x) {
        this.dwelltimes = dwelltimes_x;
    }

}
公共类运行{
公共静态void main(字符串[]args){
体素[][]body=新体素[Config.xDIM][Config.yDIM][Config.zDIM];
//东西
解算器=新解算器(实体、种子);
打印(“初始化的解算器对象!”,“通知”);
LogTool.print(“开始退火…”,“通知”);
looper.solveSA();
GlobalState GLS=looper.getGLowestState();1){
日志工具打印(“秋季1”,“通知”);
}
如果(Config.SAdebug){
LogTool.print(“SolveSA:Metropolis NewCost:+this.getNew_cost(),“notification”);
LogTool.print(“SolveSA:Metropolis CurCost:+this.getCur_cost(),“notification”);
打印(“解决成本增量”+(当前成本-新成本)+”、“通知”);
}
当前状态=新状态;
当前成本=新成本;
}否则如果(数学经验(-(当前成本-新成本)/温度)>随机双精度){
当前状态=新状态;
当前成本=新成本;
if(Config.SAdebug){
LogTool.print(“SolveSA:NewCost:+this.getNew_cost(),“通知”);
LogTool.print(“SolveSA:CurCost:+this.getCur_cost(),“通知”);
}
如果(Config.SAverboselvl>1){
LogTool.print(“秋季2:Zufallsgenerierter Zustand traegt hoehere Kosten als vorheghender Zustand.Iteration:”+x,“通知”);
}
}
温度=温度-1;
如果(温度==0){
打破
}
random_double=RandGenerator.randDouble(0.01,0.99);
newState();
设置新成本(成本());
}
如果(ab==9){
双差=0;
}
//这就是问题发生的地方-GlobalLowst成本设置正确并在整个循环中保持不变,GLowestState始终是Cur_State的最后一个值(最近完成的迭代。如果顺利运行,将是迭代9和内部迭代99)@stackexchange

如果(Cur_cost如果
GLowestState
是一个函数,那么你真的不能在它上面调用
new
——假设它是一个实现良好的单例

public enum GlobalState {
    INSTANCE;

    public String getValue() { ... }
}
如果它实现得很好,那么您可以这样称呼它:

GLowestState.getInstance();
public class Solver {
    private GlobalState GLowestState;

    public void solve() {
        GLowestState = new GlobalState(this.Cur_state);
    }

    public GlobalState  getGLowestState() {
        return GLowestState;
    }
}
另一个例子:

 GLowestState.getInstance().foo();

可以这样做:

GLowestState.getInstance();
public class Solver {
    private GlobalState GLowestState;

    public void solve() {
        GLowestState = new GlobalState(this.Cur_state);
    }

    public GlobalState  getGLowestState() {
        return GLowestState;
    }
}

如果您想让Solver成为一个单例,您需要一个私有构造函数和一个newInstance方法。 创建一个字段gloweststate并使用getter访问它

public class run {
    //stuff
    public static void main(String[] args) {
        //stuff
        Solver solver = Solver.getInstance().solve(body,seeds);
        LogTool.print("OUTPUT field of CLASS CREATED IN solver -- " + solver.getGLowestState(),"notification");
    }
}
===========
public class Solver {

    private GlobalState gLowestState;
    private static Solver singeltonSolver;

    private Solver() {

    }

    public synchronized static Solver getInstance(){
        if(singeltonSolver== null)
            singeltonSolver = new Solver();
         return singeltonSolver;
    }

    public void solve( SOmeType body,SOmeType seeds) {
        //stuff
        GlobalState GLowestState = new GlobalState(this.Cur_state);
    }

    public GlobalState getGLowestState() {
        return gLowestState;
    }
}

您需要为类内的对象实现一个
getter
,并将变量设置为
实例变量
,而不是
局部变量
。对于您的代码,示例如下:

public class Solver {
    // stuff
    GlobalState GLowestState;

    public void solve() {
        // stuff
        GLowestState = new GlobalState(this.Cur_state);
    }
    public GlobalState getGLowestState(){
        return GLowestState;
    }
}
请注意,
GLowestState
现在如何属于类的实例,而不是方法
solve()
中的局部变量

Solver solver = new Solver(body,seeds);
solver.solve();
GlobalState GS = solver.getGLowestState();

变量GS将继续
GlobalState
变量,用于
Solver
对象的特定实例。

我要做的是让
GlobalState
保持单例

public enum GlobalState {
    INSTANCE;

    public String getValue() { ... }
}
但是,
解算器
最好保留其状态,而不要弄乱全局状态

public class Solver {
    final String field;
    //stuff
    public Solver(int body, int seeds) {
        //solve stuff here
        this.field = "value";
    }
}

public class Run {
    //stuff
    public static void main(String[] args) {
        //stuff
        Solver solver = new Solver(body,seeds);
        LogTool.print("OUTPUT field of " + solver.field);
   }
}

这可以通过多种方式实现:

1-如果
GlowestState
solve()
特别相关,则仅返回它并使用返回的对象

 public GlobalState solve() {
    GlobalState globalState = new GlobalState(this.Cur_state);
    return globalState;
}
现在,您可以通过以下方式访问它:

Solver solver = new Solver(body,seeds);
GlobalState globalState = solver.solve();
2-将
GlowestState
作为一个实例并将其公开

public GlobalState glowestState;
public void solve() {
    GLowestState = new GlobalState(this.Cur_state);
}
然后,您可以通过调用solver.glowestState来获得它

3-使用getter获取
GLowestState

private GlobalState glowestState;
public void solve() {
    glowestState = new globalState(this.Cur_state);
}

public getGlowestState() {
    return GLowestState;
}

现在您可以通过调用
getGlowestState()

来获得它
GLowestState
的范围目前仅限于solve()方法。我的答案在Daniel下面如何?您需要使用
public
属性。我想提供更多的上下文。我最初有一个字段GlobalLowestState(为了简洁起见,是GLS)。如果满足某个条件,我会写入该字段-这是在solve()方法中检查的。问题是GLS采用了上次计算的Cur_状态的值,而不是全局lpowest状态的值(这是检查的目的)。我没有发现代码有任何错误,因此我将全局最低值写入了对象GLS而不是字段。奇迹般的是,GLS对象包含了正确的值。但是,即使使用get(),在solver()类之外也无法访问它。我想您的意思是
public GlobalState getGLowestState()
,类型为。在Java中,它们至少被称为字段,而不是属性。这是我最初想要实现的。我使用getter在GlobalState中获取字段的双[]。但是,如果不想使
GlobalState
可见,则GlobalState不可见(因为它是一个单独的类,您希望在
解算器
类之外使用,所以您应该),您可以更改方法以分别获取
GlobalState
对象的详细信息。例如,如果在
GlobalState
中有
int
String
,则可以使用
getGlobalStateString()
方法返回