San*_*eta 2 java parsing javaparser
我想从java代码中提取所有方法调用.我写了两个正则表达式但它们无法提取所有方法调用.
Reg1: Pattern.compile("([a-zA-Z][0-9_a-zA-Z]*\\([a-zA-Z0-9_\\s,\\[\\]\\(\\)\\.]+\\))");
Reg2: Pattern.compile("([a-zA-Z][0-9_a-zA-Z]*\\([\\s]*\\))")
输入:
"{
if ((war == null) && (config != null)) {
sb.append( &config= );
sb.append(URLEncoder.encode(config,getCharset()));
}
if ((war == null) && (localWar != null)) {
sb.append( &war= );
sb.append(URLEncoder.encode(localWar,getCharset()));
}
if (update) {
sb.append( &update=true );
}
if (tag != null) {
sb.append( &tag= );
sb.append(URLEncoder.encode(tag,getCharset()));
}
}"
Run Code Online (Sandbox Code Playgroud)
输出:
getCharset getCharset getCharset append append append
Run Code Online (Sandbox Code Playgroud)
我无法提取" encode".
有没有人有任何想法,我应该添加到正则表达式?
您需要一个Java Code Parser来执行此任务.以下是使用Java Parser的示例:
public class MethodCallPrinter
{
public static void main(String[] args) throws Exception
{
FileInputStream in = new FileInputStream("MethodCallPrinter.java");
CompilationUnit cu;
try
{
cu = JavaParser.parse(in);
}
finally
{
in.close();
}
new MethodVisitor().visit(cu, null);
}
private static class MethodVisitor extends VoidVisitorAdapter
{
@Override
public void visit(MethodCallExpr methodCall, Object arg)
{
System.out.print("Method call: " + methodCall.getName() + "\n");
List<Expression> args = methodCall.getArgs();
if (args != null)
handleExpressions(args);
}
private void handleExpressions(List<Expression> expressions)
{
for (Expression expr : expressions)
{
if (expr instanceof MethodCallExpr)
visit((MethodCallExpr) expr, null);
else if (expr instanceof BinaryExpr)
{
BinaryExpr binExpr = (BinaryExpr)expr;
handleExpressions(Arrays.asList(binExpr.getLeft(), binExpr.getRight()));
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
Method call: parse
Method call: close
Method call: visit
Method call: print
Method call: getName
Method call: getArgs
Method call: handleExpressions
Method call: visit
Method call: handleExpressions
Method call: asList
Method call: getLeft
Method call: getRight
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2433 次 |
| 最近记录: |