JDT - 如何从CompilationUnit获取ICompilationUnit

时间:2015-11-06 10:38:15

标签: java abstract-syntax-tree eclipse-jdt

这是我的代码。 我在那里制作CompilationUnit

ASTParser parser = ASTParser.newParser(AST.JLS8);
parser.setResolveBindings(true);
parser.setStatementsRecovery(true);
parser.setBindingsRecovery(true);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setEnvironment(getProjectJars(), getSrcPaths(), null, true);

parser.setSource(IOUtils.toCharArray(new FileInputStream(MY_SRC_FILE)));
parser.setUnitName(MY_SRC_FILE.getAbsolutePath());

CompilationUnit cu = (CompilationUnit) parser.createAST(null);

如何从CompilationUnit获取ICompilationUnit,它来自源代码?感谢

3 个答案:

答案 0 :(得分:0)

我找到了解决方案:

IWorkspace workspace = ResourcesPlugin.getWorkspace();
IPath path = Path.fromOSString(source.getAbsolutePath());
IFile file = workspace.getRoot().getFileForLocation(path);
ICompilationUnit compilationUnit = (ICompilationUnit) JavaCore.create(file);

答案 1 :(得分:0)

我试过这个并且有效:

ICompilationUnit cu= (ICompilationUnit)compilationUnit.getJavaElement();

答案 2 :(得分:0)

第一个选项如下:

ICompilationUnit compilationUnit = JavaCore.createCompilationUnitFrom(javaFile);  
types = compilationUnit.getAllTypes();

第二个选项如下:

IProject project = javaFile.getProject(); 
IJavaProject jProject = JavaCore.create(project); 
if (jProject == null || !jProject.exists()) 
{   
   return null; 
} 
IPackageFragment packageFragment = null; 
try {   
   packageFragment = jProject.findPackageFragment(
                         javaFile.getFullPath().removeLastSegments(1));     
   String unitName = javaFile.getName();    
   ICompilationUnit cu = packageFragment.getCompilationUnit(unitName);  
   return cu; 
} catch (JavaModelException e) {    
return null; 
}