Eclipse:提取方法功能失败

hto*_*que 1 java eclipse refactoring

为了更好地阅读冗长的方法,我想用一个方法替换重复使用的代码块(仅赋值).因此,我选择了代码块并运行了Eclipse的Extract Method功能,但是由于此错误而失败:

不明确的返回值:所选块包含多个局部变量赋值.受影响的变量是:

int foo
double[] bar
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题?它应该是一个简单的void方法做一些任务,我不确定Eclipse(3.6.2)抱怨什么.

sta*_*ker 5

Eclipse需要所有用作参数的变量,并返回在提取的块中修改的一个或没有变量.

你发的是一个类似的结构

void f2() {
        int a,b;
        int foo=0;                           // selection start
        double[] bar = new double[10];
        for ( int i = 0 ; i < bar.length ; i++ ) {
            bar[i] = foo;
        }
        foo = 0;                             // selection end

        a = foo;
        b = (int) bar[0];
    }
Run Code Online (Sandbox Code Playgroud)

由于在进一步的语句中需要两个变量(foo,bar),因此它们不能作为一个值返回.你可以返回一个包含foo和bar的类.

将它们声明为成员变量是有效的

public class Refactor {
    int foo ;
    double[] bar; 

    void f2() {
        for ( int i = 0 ; i < bar.length ; i++ ) {        // selection start
            bar[i] = foo;
        }
        foo = 0;                                          // selection end
    }
}
Run Code Online (Sandbox Code Playgroud)

以及:

void f2() {
        int foo=0;                                  // selection start
        double[] bar = new double[10];
        for ( int i = 0 ; i < bar.length ; i++ ) {
            bar[i] = foo;
        }
        foo = 0;                                    // selection end
    }
Run Code Online (Sandbox Code Playgroud)