Java. Function (final) of the variable in the try-block and its further use and visibility



  • The problem is the need to assign the final variable (connectionSocket2) to the test block. In the following part of the code run()() This is not visible and there is a mistake that the variable is not defined:

            final Socket connectionSocket;
            try { connectionSocket = welcomeSocket.accept(); }
    

    The local variable connectionSocket2 may not have been initialized

    Take it away. final I can't because run()Makes a mistake

    Cannot refer to the non-final local variable connectionSocket defined in an enclosing scope

                Socket connectionSocket2=null;
                try { connectionSocket2 = welcomeSocket.accept();
                } catch (IOException e2) { e2.printStackTrace(); }
                final Socket connectionSocket=connectionSocket2; try{connectionSocket2.close();}catch(IOException e1){e1.printStackTrace();}
    
            service.submit(new Runnable() {
                public void run() {
                    while (true) {
                        BufferedReader inFromClient=null;
                        DataOutputStream outToClient=null;
                        try{
                           inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
                           outToClient = new DataOutputStream(connectionSocket.getOutputStream());
                           outToClient.writeBytes(inFromClient.readLine());
                        } catch(IOException ioe) {} }}});
    

    I can't do static. For each flow, I'm creating a connection, like a copy of this variable.

    The code used, used the second variable to transfer its value and to continue using the second variable. But it looks bad.

    Is it right to be professional in this situation? Is there any way to tell the compilator that the variable is actually already defined in the bloc and has nothing to worry about?



  • We can do this:

    public class MySocket{
        private Socket  mSocket;
        public MySocket(){
        }
    
    public void setSocket(Socket socket){
        mSocket = socket;
    }
    
    public Socket getSocket(){
        return mSocket;
    }
    

    }

    And create a copy of it:

    final MySocket connectionSocket = new MySocket();

    And then...

    try{
    connectionSocket.setSocket(welcomeSocket.accept());
    } catch (IOException e2) {
    e2.printStackTrace();
    }

    And inside Runnable request connectionSocket.getSocket()




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2