使用JDT删除方法
问题描述:
我正在创建一个实用程序来检测代码库中未使用的方法。通过使用下面的代码,我能够成功地找到未使用的方法(没有引用)。但我也需要删除这些未使用的方法。请让我知道是否可以通过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
}
}
}
答
关于IMethod的)从ISourceManipulation的Javadoc它有一个方法删除(。
看到:
答
一般ASTRewrite用于修改源。你可以看看执行 '删除未使用的方法' 速战速决 -
org.eclipse.jdt.internal.corext.fix.UnusedCodeFix.RemoveUnusedMemberOperation.removeUnusedName(CompilationUnitRewrite, SimpleName)
您也可以使用JDT的Clean-Up来执行此操作,请参阅“源代码>清理>不必要的代码>删除未使用的私人成员'
+1。我其实在我的代码中尝试了IMethod.delete(),但删除并未反映在实际的代码中。 – 2012-04-25 04:36:46
我刚刚发现了ICompilationUnit.commit方法。似乎我必须在更改后提交该文件。经过相同的测试后会回复给你。 – 2012-04-25 09:14:18
忙于其他一些工作。我通过扩展ASTVisitor类来使用不同的方法。在Visitor类中使用node.delete()来删除该方法。使用RecordModification用更改来更新JavaClass。然后做了一个手动重写的java文件。 – 2012-05-18 10:17:42