Java process problem in Eclipse

This is my code:

final String run_tool ="cmd.exe /C pelda.exe";
final Process tool_proc = null;

Runnable doRun = new Runnable() {
    public void run() {
        try {
            tool_proc = Runtime.getRuntime().exec(run_tool);
            } 
        catch (IOException e) {
            e.printStackTrace();
        }
    }
};    

Thread th = new Thread(doRun);
th.start();

InputStream toolstr = tool_proc.getInputStream();

After eclipse issues this warning, remember the tool_proc variable:

The last local variable tool_proc cannot be assigned because it is defined in the enclosing type

I don't know why my code is not working

Please help me

+3
source share
4 answers

The modifier finalforbids changing the variable after setting it. Kevin gives an excellent explanation of why you cannot use it in this context.

For the construction of your choice, you need to enter the field of the parent class and set it via run():

class MyClass {
    Process tool_proc = null;

    void myFunction() {
        final String run_tool ="cmd.exe /C pelda.exe";
        Runnable doRun = new Runnable() {
            public void run() {
                try {
                    tool_proc = Runtime.getRuntime().exec(run_tool);
                    } 
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        Thread th = new Thread(doRun);
        th.start();

        // tool_proc will be null at this point!
        InputStream toolstr = tool_proc.getInputStream();
    }
}

, tool_proc null , !

NullPointerException s!


, , . , . , StreamGobbler ( . 4).

+6

, ++- java:

final String run_tool ="cmd.exe /C pelda.exe";
final Process tool_proc[] = new Process[1];

Runnable doRun = new Runnable() {
    public void run() {
        try {
            tool_proc[0] = Runtime.getRuntime().exec(run_tool);
            } 
        catch (IOException e) {
            e.printStackTrace();
        }
    }
};    

Thread th = new Thread(doRun);
th.start();

InputStream toolstr = tool_proc.getInputStream();
+2

tool_proc final - , null . null , runnable , . , - final, ,

, , tool_proc - , final Runnable. , Process.

+1

The initial value of the final field cannot be changed. Delete the final modifier from the proc tool:

Process tool_proc = null;
-2
source

Source: https://habr.com/ru/post/1737234/


All Articles