TheCoder
TheCoder

Reputation: 8913

Static Lazy Initializer

I have a class that configures a server. The server object is static and is lazy initialised. The issue is, some of the config for the server comes from non-static member variables of the containing class. Obviously, the non-static members cannot be accessed. Is there a way around this, that I can configure my server using non-static variables? The server must remain static.

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;
    }
}

Upvotes: 0

Views: 144

Answers (1)

user7391763
user7391763

Reputation:

From your question, I understood it as something like below;

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;
   }
}

Upvotes: 1

Related Questions