2010-02-26 117 views

回答

3

你可以在this thread使用的代碼,並使用VariableDeclarationFragment

public boolean visit(VariableDeclarationStatement node) 
    { 
     System.out.println("Visiting variable declaration statement."); 
     for(int i = 0; i < node.fragments().size(); ++i) 
     { 
      VariableDeclarationFragment frag = (VariableDeclarationFragment)node.fragments().get(i); 
      System.out.println("Fragment: " + node.getType() + " " + frag.getName()); 
     } 

     System.out.println("");   
     return true; 
    } 

要獲得在這個(變量)定義的方法,我會用的訪問者CompilationUnit,查找VariableDeclarationFragment,同時記憶IMethod我目前解析:

 IJavaElement element = delta.getElement(); 

     if(element.getElementType() != IJavaElement.COMPILATION_UNIT) 
      return; 

     ICompilationUnit compilationUnit = (ICompilationUnit)element; 

     try 
     { 

      IType type = compilationUnit.findPrimaryType(); 
      IMethod[] methods = type.getMethods(); 
      for(IMethod method : methods) 
      {     
       ASTParser parser = ASTParser.newParser(AST.JLS3);     
       parser.setSource(compilationUnit); 
       parser.setSourceRange(method.getSourceRange().getOffset(), method.getSourceRange().getLength()); 
       //parser.setKind(ASTParser.K_CLASS_BODY_DECLARATIONS); 
       //parser.setSource(method.getSource().toCharArray()); 
       //parser.setProject(method.getJavaProject());     
       parser.setResolveBindings(true); 
       CompilationUnit cu = (CompilationUnit)parser.createAST(null); 
       cu.accept(new ASTMethodVisitor()); 

       // If the visitor visit the right VariableDeclarationFragment, 
       // then the right IMethod is the current 'method' variable 

      }       
     } 
     catch(JavaModelException e) 
     {   
      e.printStackTrace(); 
     }   
+0

但是,這將使該變量的名字和類型。我想要的方法名也是這樣的: – Steven 2010-02-26 05:36:12

+0

@Nishan:剛剛添加了訪問者策略來查找定義了'VariableDeclarationStatement'的'IMethod'。 – VonC 2010-02-26 06:51:26

+0

我沒有得到它。任何鏈接oe例如請 – Steven 2010-02-26 08:26:10