有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java源代码中使用ASTParser解析Catch子句

我正在使用Java语法分析器来解析我的Java代码。我正在使用以下代码。使用此代码,我可以提取“如果”&;“try”语句。但我无法提取“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) 个答案

  1. # 1 楼答案

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

    返回true,它就会工作

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