gpt4 book ai didi

java - 静态惰性初始化器

转载 作者:行者123 更新时间:2023-12-02 13:19:07 28 4
gpt4 key购买 nike

我有一个配置服务器的类。服务器对象是静态的并且是延迟初始化的。问题是,服务器的一些配置来自包含类的非静态成员变量。显然,非静态成员是无法访问的。有没有办法解决这个问题,我可以使用非静态变量配置我的服务器?服务器必须保持静态。

public class ClassA {

private static MyServer myServer;
private int a;
private int b;

public ClassA(int a, int b) {
this.a = a;
this.b = b;
}

public static MyServer getMyServer() {

if(myServer == null) {
myServer = configureServer();
}

return myServer;
}

private static MyServer configureServer() {
MyServer myServer = new MyServer();
myServer.setaPlusB(a + b);

return myServer;
}

}

public class MyServer {

private int aPlusB;

public void setaPlusB(int aPlusB) {
this.aPlusB = aPlusB;
}
}

最佳答案

根据你的问题,我的理解如下;

public class Server {

private class ServerImpl {

private int ab;

public ServerImpl() {

ab = Server.a + Server.b;
}
}

private static int a;
private static int b;
private static ServerImpl s;

static {

a = 10;
b = 10;
}

public static ServerImpl getServer(int newA, int newB) {

a = newA;
b = newB;
return getServer();
}

public static ServerImpl getServer() {

if (s == null) {
s = new ServerImpl();
}
return s;
}
}

关于java - 静态惰性初始化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43642059/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com