Unni Kris
Unni Kris

Reputation: 3095

Delete a method using JDT

I am creating a utility to detect unused methods in a code base. By using the below code i am able to succesfully find the unused methods (having no references) . But i also need to delete such unused methods. Please let me know if it is possible through 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
         }
     }
}

Upvotes: 1

Views: 870

Answers (2)

Deepak Azad
Deepak Azad

Reputation: 7923

Usually ASTRewrite is used to modify source. You can take a look at the implementation of 'Remove unused method' quick fix -

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

You can also just use the Clean-Up from JDT to do this, see 'Source > Clean up > Unnecessary Code > Remove unused private members'

Upvotes: 0

Andreas
Andreas

Reputation: 1193

Regarding the Javadoc of IMethod it has a method delete() from ISourceManipulation.

see:

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

Upvotes: 2

Related Questions