在Java源代码中使用ASTParser提取Catch子句

时间:2014-08-16 13:54:55

标签: java parsing

我正在使用Java ASTParser来解析我的java代码。我正在使用以下代码。使用此代码,我能够提取"如果" &安培; "尝试"声明。但我无法提取" catch条款"。有没有人知道如何在此单独提取catch子句。以下代码没有给出任何错误,但它没有在catch子句中打印任何内容。

public static void methodVisitor(String content) 
{
   //debug("entering met visitor", "1");
   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(IfStatement myif) {          
         System.out.println("myif="+myif.toString());
         return false;
      }


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

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

   });
}

以下是我尝试查询的示例代码:

     public class Clock2 extends Applet implements Runnable {
     private static final long serialVersionUID = 1L;
      Thread timer;                // The thread that displays clock
   int lastxs, lastys, lastxm,
    lastym, lastxh, lastyh;  // Dimensions used to draw hands
SimpleDateFormat formatter;  // Formats the date displayed
String lastdate;             // String to hold date displayed
Font clockFaceFont;          // Font for number display on clock
Date currentDate;            // Used to get date to display
Color handColor;             // Color of main hands and dial
Color numberColor;           // Color of second hand and numbers

@Override
public void init() {
    lastxs = lastys = lastxm = lastym = lastxh = lastyh = 0;
    formatter = new SimpleDateFormat ("EEE MMM dd hh:mm:ss yyyy", Locale.getDefault());
    currentDate = new Date();
    lastdate = formatter.format(currentDate);
    clockFaceFont = new Font("Serif", Font.PLAIN, 14);
    handColor = Color.blue;
    numberColor = Color.darkGray;

    try {
        setBackground(new Color(Integer.parseInt(getParameter("bgcolor"),16)));
    } catch (Exception e) {
        // Ignore
    }
    try {
        handColor = new Color(Integer.parseInt(getParameter("fgcolor1"),16));
    } catch (Exception e) {
        // Ignore
    }
    try {
        numberColor = new Color(Integer.parseInt(getParameter("fgcolor2"),16));
    } catch (Exception e) {
        // Ignore
    }
    resize(300,300);              // Set clock window size
}

}

1 个答案:

答案 0 :(得分:0)

它是因为在访问您的IfStatement节点后返回false,因此解析器不会在您的节点内进行探索。

返回true,它会起作用。

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