简体   繁体   中英

Extracting a method in eclipse doesn't seem to work

I try to do a simple refactoring (extract method) in eclipse. I select the following code block and do a alt+shift+M (shortcut for extracting).

    Parser parser = Parser.createParser(comment.getText(), "UTF-8");
    NodeList htmlAnchorNodes = null;
    try {
        htmlAnchorNodes = parser
                .extractAllNodesThatMatch(new TagNameFilter("a"));
    } catch (ParserException e) {
        e.printStackTrace();
    }

    int size = htmlAnchorNodes.size();

Only the size variable is used afterwards.

I get the error message:

Ambiguous return value: Selected block contains more than one assignment to local variables. Affected variables are:

NodeList htmlAnchorNodes

Parser parser

int size

How can I get Eclipse to recognize the return value?

In some cases Eclipse isn't sure which variable you intend to return. It would be ideal if it would prompt you to select one, or do an analysis based on which value is actually used later, but I've worked around it by using braces to limit the scope of the temporary values before extracting the method.

With your code, I would change from

Parser parser = Parser.createParser(comment.getText(), "UTF-8");
NodeList htmlAnchorNodes = null;
try {
    htmlAnchorNodes = parser
            .extractAllNodesThatMatch(new TagNameFilter("a"));
} catch (ParserException e) {
    e.printStackTrace();
}

int size = htmlAnchorNodes.size();

to

int size;

{
    Parser parser = Parser.createParser(comment.getText(), "UTF-8");
    NodeList htmlAnchorNodes = null;
    try {
        htmlAnchorNodes = parser
                .extractAllNodesThatMatch(new TagNameFilter("a"));
    } catch (ParserException e) {
        e.printStackTrace();
    }
    size = htmlAnchorNodes.size();
}

The only assignment which has an effect outside of the scope of the braces is the change to size , which should resolve the ambiguity for the refactoring tool.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM