Gin*_*ead 14 java eclipse refactoring
我需要在很长一段时间内重构代码.我知道从Eclipse IDE里面我可以重构我的类.但是我可以在java项目中使用任何API,以便我可以通过代码动态地重构项目吗?
我需要了解如何实现以下内容:一个程序调用所有Eclipse重构进行重命名并在循环中移动以一次重构整个项目!
我不想通过扩展重构类来引入新的重构类型.我只是想以编程方式调用它们.
小智 14
像这样的东西?
任何在基于Eclipse的IDE中支持编程语言的人迟早都会被要求提供自动重构 - 类似于Java开发工具(JDT)提供的内容.自Eclipse 3.1发布以来,语言中性API(语言工具包(LTK))至少支持此任务的一部分(这绝不是简单的).但是这个API是如何使用的呢?
编辑:
如果要在不使用UI的情况下以编程方式运行重构,可以使用RefactoringDescriptors(请参阅文章)填写参数并以编程方式执行重构.如果您创建一个依赖于org.eclipse.core.runtime并添加org.eclipse.core.runtime.applications扩展的插件,您将能够IApplication从eclipse 运行类似于main(String[])普通java应用程序中的类.可以在帖子上找到调用API的示例.
ICompilationUnit cu = ... // an ICompilationUnit to rename
RefactoringContribution contribution =
RefactoringCore.getRefactoringContribution(IJavaRefactorings .RENAME_COMPILATION_UNIT);
RenameJavaElementDescriptor descriptor =
(RenameJavaElementDescriptor) contribution.createDescriptor();
descriptor.setProject(cu.getResource().getProject().getName( ));
descriptor.setNewName("NewClass"); // new name for a Class
descriptor.setJavaElement(cu);
RefactoringStatus status = new RefactoringStatus();
try {
Refactoring refactoring = descriptor.createRefactoring(status);
IProgressMonitor monitor = new NullProgressMonitor();
refactoring.checkInitialConditions(monitor);
refactoring.checkFinalConditions(monitor);
Change change = refactoring.createChange(monitor);
change.perform(monitor);
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
如果您有关于使用JDT API(AST,Refactoring等)的更详细的问题,我建议您在JDT论坛上提问.
下面的答案是很好的,但我更广泛地回答了那些需要更加笨重和美味的人们cake:
RefactoringStatus status = new RefactoringStatus();
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot root = workspace.getRoot();
IProject[] projects = root.getProjects();
Run Code Online (Sandbox Code Playgroud)
然后:
for (ICompilationUnit unit : mypackage.getCompilationUnits()) {
IType primary = unit.findPrimaryType();
IMethod[] methods = primary.getMethods();
int i = 1;
for (IMethod method : methods) {
if (method.isConstructor()) {
continue;
}
makeChangetoMethods(status, method,"changedMethodVersion_" + i);
++i;
}
}
Run Code Online (Sandbox Code Playgroud)
之后:
IProgressMonitor monitor = new NullProgressMonitor();
status = new RefactoringStatus();
Refactoring refactoring = performMethodsRefactoring(status, methodToRename, newName);
Run Code Online (Sandbox Code Playgroud)
然后:
Change change = refactoring.createChange(monitor);
change.perform(monitor);
Run Code Online (Sandbox Code Playgroud)
在下面找到用于设置的代码descriptor:
String id = IJavaRefactorings.RENAME_METHOD;
RefactoringContribution contrib = RefactoringCore.getRefactoringContribution(id);
RenameJavaElementDescriptor desc = contrib.createDescriptor();
desc.setUpdateReferences(true);
desc.setJavaElement(methodToRename);
desc.setNewName(newName);
desc.createRefactoring(status);
Run Code Online (Sandbox Code Playgroud)