2014-08-30 69 views
2

我想从java代码中提取所有捕获块。我能够提取正常的try-catch块,但是如果catch块嵌套在其他类型的块中,比如“if”,我的代码就能检测到它们。在Java代码中提取嵌套捕获块

以下是我一直在使用AST解析器编写的代码:

public static void methodVisitor(String content) 
{ 
    ASTParser metparse = ASTParser.newParser(AST.JLS3); 
    metparse.setSource(content.toCharArray()); 
    metparse.setKind(ASTParser.K_STATEMENTS); 
    Block block = (Block) metparse.createAST(null); 

    block.accept(new ASTVisitor() 
    { 
     public boolean visit(VariableDeclarationFragment var) 
     { 
      return false; 
     } 

     public boolean visit(SimpleName node) 
     { 
      return false; 
     } 

     public boolean visit(IfStatement myif) 
     { 
      System.out.println("myif=" + myif.toString()); 
      return false; 
     } 

     public boolean visit(TryStatement mytry) 
     { 
      System.out.println("mytry=" + mytry.toString()); 
      List catchClauses = mytry.catchClauses(); 

      CatchClause clause = (CatchClause) catchClauses.get(0); 
      SingleVariableDeclaration exception = clause.getException(); 
      Type type = exception.getType(); 

      System.out.println("catch=" + catchClauses.toString()); 

      return false; 
     } 

     public boolean visit(CatchClause mycatch) 
     { 
      System.out.println("mycatch=" + mycatch.toString()); 
      return false; 
     } 
    }); 
} 

此代码是不能够提取的catch子句中以下条件:

if (base != null && base.getClass().isArray()) 
{ 
    context.setPropertyResolved(base, property); 
    try 
    { 
     int idx = coerce(property); 
     checkBounds(base, idx); 
    } 
    catch (IllegalArgumentException e) 
    { 
    } 
} 

有谁知道如何提取嵌套抓块。 谢谢!提前!!

+2

“AST解析器”部分是什么工具?我的猜测(我不知道你的工具集)是你的“访问者”是集体走路的树,并且“访问(IfStmt ..)”返回“false”导致树行走中止if声明已经公布。这会阻止递归到嵌套的“try”子句隐藏的“if”的子部分。尝试使“vist(IfStmt ...)”返回“true”(它可能需要呼叫访问其子女?)。 – 2014-08-30 05:12:26

+0

谢谢!工作:-) – Sangeeta 2014-08-30 05:26:57

回答

1

我的猜测(我不知道你的工具集)是你的“访客”是集体走树,而“访问(IfStmt ..)”返回“假”导致树行走到在if语句树节点被引用时中止。

这将防止递归到嵌套的“try”子句隐藏的“if”的子部分。

尝试使“vist(IfStmt ...)”返回“true”(它可能需要调用其子对象访问?)。

+0

嗨艾拉,我想问一件事。如果我想提取所有的catch块,我是否需要为所有类型的块创建访问者,“if”,“switch”等。 – Sangeeta 2014-08-30 05:43:58

+1

不是我的包,这是一个基于有多少这样的工作有教育的猜测。所以我只能说,可能是的。我认为你应该更仔细地阅读访问者的文档。 – 2014-08-30 06:00:44