我正在创建一个Eclipse插件来重命名Types,Methods和Fields。使用以下代码我可以重命名类和源文件,但我不知道如何在其他类中找到该类的用法。
ITextEditor editor = (ITextEditor) PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage().getActiveEditor();
ITextSelection selection = (ITextSelection) editor
.getSelectionProvider().getSelection();
IEditorInput editorInput = editor.getEditorInput();
IJavaElement elem = JavaUI.getEditorInputJavaElement(editorInput);
if (elem instanceof ICompilationUnit) {
ICompilationUnit unit = (ICompilationUnit) elem;
IJavaElement selected = null;
try {
selected = unit.getElementAt(selection.getOffset());
} catch (JavaModelException e) {
e.printStackTrace();
}
if(selected.getElementType() == IJavaElement.TYPE) {
IType type = (IType) selected;
InputDialog input = new InputDialog(HandlerUtil.getActiveShell(event), "Rename...",
"Enter the new name for Type: " + selected.getElementName() , selected.getElementName(), null);
if(input.open() == InputDialog.OK)
{
try {
type.rename(input.getValue(), true, null);
} catch (JavaModelException e) {
e.printStackTrace();
}
}
}
}
答案 0 :(得分:2)
您可以使用JDT Core的SearchEngine API
答案 1 :(得分:2)
我有许多有用的Eclipse JDT搜索方法here,它们使用了SearchEngine等。例如:
/**
* Find all classes that access methods or fields in this class
* from within the same project.
* @param element the Java element the search pattern is based on
* @param scope the elements being examined, e.g. this class or this package
* @return the handles of the classes that have methods that
* reference methods or fields in this class
*/
public static Set<String> calculateCallingClasses(IJavaElement element,
IJavaSearchScope scope)
throws CoreException {
SearchEngine engine = new SearchEngine();
SearchParticipant[] participants =
new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() };
SearchPattern pattern =
SearchPattern.createPattern(element, REFERENCES);
IType enclosingType =
(IType)element.getAncestor(IJavaElement.TYPE);
ClientClassCollector collector = new ClientClassCollector(enclosingType);
try{
engine.search(pattern, participants, scope, collector, null);
} catch (Exception e) {
System.err.println(e.toString() + " for " + element.getElementName());
}
Set<String> clients = collector.getResult();
return clients;
}