2012-04-23 39 views
1

我正在創建一個實用程序來檢測代碼庫中未使用的方法。通過使用下面的代碼,我能夠成功地找到未使用的方法(沒有引用)。但我也需要刪除這些未使用的方法。請讓我知道是否可以通過JDT。使用JDT刪除方法

// Get all the type declaration of the class. 
IType [] typeDeclarationList = unit.getTypes(); 

for (IType typeDeclaration : typeDeclarationList) { 
    // Get methods under each type declaration. 
    IMethod [] methodList = typeDeclaration.getMethods(); 

    for (IMethod method : methodList) { 

      final List<String> referenceList = new ArrayList<String>(); 

      // loop through the methods and check for each method. 
      String methodName = method.getElementName(); 
      if (!method.isConstructor()) { 

       // Finds the references of the method and returns the references of the method. 
       JDTSearchProvider.searchMethodReference(referenceList, method, scope, iJavaProject); 
      } 
     if (referenceList.isEmpty()) { 
       // delete method 
     } 
    } 
} 

回答

2

關於IMethod的)從ISourceManipulation的Javadoc它有一個方法刪除(。

看到:

http://help.eclipse.org/galileo/index.jsp?topic=/org.eclipse.jdt.doc.isv/reference/api/org/eclipse/jdt/core/IMethod.html

+0

+1。我其實在我的代碼中嘗試了IMethod.delete(),但刪除並未反映在實際的代碼中。 – 2012-04-25 04:36:46

+0

我剛剛發現了ICompilationUnit.commit方法。似乎我必須在更改後提交該文件。經過相同的測試後會回覆給你。 – 2012-04-25 09:14:18

+0

忙於其他一些工作。我通過擴展ASTVisitor類來使用不同的方法。在Visitor類中使用node.delete()來刪除該方法。使用RecordModification用更改來更新JavaClass。然後做了一個手動重寫的java文件。 – 2012-05-18 10:17:42

0

一般ASTRewrite用於修改源。你可以看看執行 '刪除未使用的方法' 速戰速決 -

org.eclipse.jdt.internal.corext.fix.UnusedCodeFix.RemoveUnusedMemberOperation.removeUnusedName(CompilationUnitRewrite, SimpleName)

您也可以使用JDT的Clean-Up來執行此操作,請參閱「源代碼>清理>不必要的代碼>刪除未使用的私人成員'