0

我正在尝试使用 CheckStyle 检索在给定源文件中找到的所有方法中的所有参数名称。以下是相关代码:


public int[] getDefaultTokens()
{
   return new int[] { TokenTypes.METHOD_DEF};
}


public void visitToken(DetailAST aDetailAST)
{
String returnType;        // The return type of the method.
int numberOfParameters;   // The number of parameters in the method's parameter list... not    returned in log.
String [] parameterNames; // The names of all method parameters.
int openingBraceLine;     // The line number of the opening method bracket.

  returnType = aDetailAST.findFirstToken(TokenTypes.TYPE).getFirstChild().getText(); // get the return type.

  numberOfParameters = aDetailAST.findFirstToken(TokenTypes.PARAMETERS).getChildCount(TokenTypes.PARAMETER_DEF); // get num of parameters.
  parameterNames = new String[numberOfParameters]; // create array to store the parameter names.
  if (numberOfParameters > 0) // only bother if parameters existed.
  {
     List <DetailAST> parameters = DetailASTUtil.getDetailASTsForTypeInBranch                       // Get all PARAMETER_DEF nodes.
                                             (aDetailAST.findFirstToken(TokenTypes.PARAMETERS)
                                                                  , TokenTypes.PARAMETER_DEF);

     int i = 0;

     for (DetailAST currentParameter: parameters) // iterate through all parameters.
     {
        parameterNames[i] = currentParameter.findFirstToken(TokenTypes.IDENT).getText();
        // Get the parameter name, store it in the array.
        i++; // iterate to next parameter name array storage index.
     }
  }

  // parameterNames now contains all parameter names in the parameter list. Format it for log message.

  String formattedParameterNames = "";


  if (numberOfParameters > 1) // if more than one parameter was present, then create comma list.
  {
     for (int i = 0; i < parameterNames.length-1; i++) // put all names in comma-separated string except for last.
     {
        formattedParameterNames += parameterNames[i] + ", ";
     }

     formattedParameterNames += parameterNames[numberOfParameters-1]; // add the last element of the comma list.
  }
  else if (numberOfParameters == 1) // only one parameter -- don't comma-delimit.
  {
     formattedParameterNames = parameterNames[0];
  }

  if (numberOfParameters == 2) // debug to see if string formatting is messing up the parameter names or if tree traversal is bad.
  {
     formattedParameterNames = "Param 1: " + parameterNames[0] + " Param 2: " + parameterNames[1];
  }

  log(aDetailAST.getLineNo(), "[" + returnType + "]" + ", [" + formattedParameterNames + "], ");
  // will be further parsed in actual applet since I don't think there's a way to get individual lines of code via CheckStyle... I would like if a getTextForLineofCode(lineNumber) func existed with CheckStyle, but I don't think it does.
}

public static List<DetailAST> getDetailASTsForTypeInBranch(DetailAST expr,
        int tokenType) {
    return getDetailASTsForTypeInBranch(expr, tokenType, null);
}

private static List<DetailAST> getDetailASTsForTypeInBranch(DetailAST expr,
        int tokenType, List<DetailAST> list) {
    if (list == null)
        list = new ArrayList<DetailAST>();
    DetailAST child = (DetailAST) expr.getFirstChild();
    while (child != null) {
        if (child.getType() == tokenType) {
            list.add(child);
        } else {
            list = getDetailASTsForTypeInBranch(child, tokenType, list);
        }
        child = (DetailAST) child.getNextSibling();
    }
    return list;
}

当我在主小程序中检索此日志消息时,没有/单参数列表的函数看起来很好,但双参数函数要么根本没有注册,要么返回消息“secondParmeterNameHere]”,其中 secondParameterNameHere 是特定函数的第二个参数名称。

关于我获取所有参数名称的算法有什么问题的任何想法?谢谢。

4

2 回答 2

0

我的两分钱来优化你的代码。

使用 for 循环

在您的递归辅助方法中,您可以替换

    DetailAST child = (DetailAST) expr.getFirstChild();
while (child != null) {
    if (child.getType() == tokenType) {
        list.add(child);
    } else {
        list = getDetailASTsForTypeInBranch(child, tokenType, list);
    }
    child = (DetailAST) child.getNextSibling();
}

经过

for(DetailAST child = (DetailAST) expr.getFirstChild(); child != null; child = (DetailAST) child.getNextSibling()) {
    if (child.getType() == tokenType) {
        list.add(child);
    } else {
        list = getDetailASTsForTypeInBranch(child, tokenType, list);
    }
}

决定一种分配“列表”的方法

这是某种“分配重复:

list = getDetailASTsForTypeInBranch(child, tokenType, list);

您通过引用传递“列表”。并且在递归期间,您对该引用进行操作(list.add(..))。但是您稍后仍会将此列表作为返回值返回。在递归中,您将此返回值重新分配给原始输入变量,尽管在递归期间已对其进行了修改?!

您应该使用返回值并且不要将列表作为输入参数传递。或者你可以传递列表,但你的方法不应该有返回值。

减少代码以格式化参数名称

变量parameterNames已过时,因为您只使用它再次迭代它并连接一个字符串。您的字符串连接也重复且效率低下。我会提出以下解决方案:

        StringBuilder formattedParameterNames = new StringBuilder();
    for (Iterator<DetailAST> iterator = parameters.iterator(); iterator.hasNext();) {
        DetailAST detailAST = iterator.next();
        formattedParameterNames.append(detailAST.findFirstToken(TokenTypes.IDENT).getText());
        if(iterator.hasNext()) {
            formattedParameterNames.append(", ");
        }
    }

您可以在 StringBuilder 上调用 toString() 来获取您的日志记录语句。

于 2012-06-18T12:21:32.433 回答
0

希望下面的代码片段对您有所帮助

@Override
public int[] getDefaultTokens() {
    return new int[] { TokenTypes.METHOD_DEF};
}


@Override
public void visitToken(DetailAST ast) {
    String methodName = null;
    String returnType = null;
    int numberOfParameters = 0;

    methodName = ast.findFirstToken(TokenTypes.IDENT).getText();

    DetailAST typeElt = ast.findFirstToken(TokenTypes.TYPE);
    returnType = typeElt.getFirstChild().getText();

    DetailAST parametersElt = ast.findFirstToken(TokenTypes.PARAMETERS); 
    numberOfParameters = parametersElt.getChildCount(TokenTypes.PARAMETER_DEF);

    log(ast,"Method Name : "+methodName);
    log(ast,"Return Type : "+returnType);
    log(ast,"No Of Parameters : "+numberOfParameters);

    DetailAST paraElt = parametersElt.findFirstToken(TokenTypes.PARAMETER_DEF);

    int i=1;
    while(paraElt != null){
        if(paraElt.getType() == TokenTypes.PARAMETER_DEF){
            String dataType = paraElt.findFirstToken(TokenTypes.TYPE).getFirstChild().getText();
            String paraName = paraElt.findFirstToken(TokenTypes.IDENT).getText();
            log(ast,"Parameter "+i+" ("+dataType+" "+paraName+")");
            i++;    
        }
        paraElt = paraElt.getNextSibling();
    }
}

输出将像

[ERROR] path\Test.java:8:9: Method Name : add [ListMethodParameters]
[ERROR] path\Test.java:8:9: No Of Parameters : 0 [ListMethodParameters]
[ERROR] path\Test.java:8:9: Return Type : void [ListMethodParameters]
[ERROR] path\Test.java:12:9: Method Name : sub [ListMethodParameters]
[ERROR] path\Test.java:12:9: No Of Parameters : 3 [ListMethodParameters]
[ERROR] path\Test.java:12:9: Parameter 1 (int a) [ListMethodParameters]
[ERROR] path\Test.java:12:9: Parameter 2 (int b) [ListMethodParameters]
[ERROR] path\Test.java:12:9: Parameter 3 (int c) [ListMethodParameters]
[ERROR] path\Test.java:12:9: Return Type : int [ListMethodParameters]

Java文件用于测试上述代码

public class Test {
    public void add(){
        name.length();
    }
    public int sub(int a,int b,int c){
        return a+b+c;
    }
}
于 2019-12-13T13:52:46.477 回答