如何将AST转换为JDT Java模型 [英] How to convert AST to JDT Java model
问题描述
此问题显示了如何创建AST模型但是我不知道如何将它转换为Java模型?
我的代码如下所示:
String source =
package com.test\\\
+
\\\
+
import com.test .something; +
\\\
+
public class Class {\\\
+
int sum(int a,int b)\\\
+
} \\\
;
ASTParser parser = ASTParser.newParser(AST.JLS4);
parser.setSource(source.toCharArray());
CompilationUnit unit =(CompilationUnit)parser.createAST(null);
所以我有一个 CompilationUnit
的实例,但是我需要一个ICompilationUInit的实例,所以我可以访问 IMethod
和 IType
对象。
这不是真的可能。 ICompilationUnit
是java模型的一部分,这意味着它是某个地方的Java项目的一部分,并具有完整的类路径,一个包,一个包根等等。正在做的是创建一个没有连接到任何java项目的文本的解析树。
如果你可以更具体地说明你的目标是什么,那可能是您不需要任何IType和IMethod实例的情况。
或者,如果您确实需要这些类型的实例,那么您将需要生成 IProject
s,添加一个java性质,然后用文件填充。最好的方法是查看JDT测试基础架构的工作原理。
以及如何在整个测试框架中使用。
I am writing unit tests for my plugin that makes use of IType and IMethod interfaces from JDT. To write unit tests I would need to instantiate such interfaces. Answer to this question shows how to create AST model, but I don't know how to convert it into Java model?
My code looks like this:
String source =
"package com.test\n" +
"\n" +
"import com.test.something;" +
"\n" +
"public class Class{\n" +
"int sum(int a, int b)\n" +
"}\n";
ASTParser parser = ASTParser.newParser(AST.JLS4);
parser.setSource(source.toCharArray());
CompilationUnit unit = (CompilationUnit) parser.createAST(null);
So I have an instance of CompilationUnit
, but I need an instance of ICompilationUInit, so I can get access to IMethod
and IType
objects.
This is not really possible. ICompilationUnit
s are part of the java model, which means that it is part of a Java project somewhere and has a full classpath, a package, a package root, etc. All you are doing is creating a parse tree of some text that is not connected to any java project.
If you can be more specific about what your goal is, it might be the case that you don't really need any IType and IMethod instances.
Or, if you really do need instances of these types, then you will need to generate IProject
s, add a java nature to it, and then populate it with files. Your best bet is to see how the JDT test infrastructure works.
Take a look at this file: https://github.com/eclipse/eclipse.jdt.core/blob/master/org.eclipse.jdt.core.tests.builder/src/org/eclipse/jdt/core/tests/builder/TestingEnvironment.java
and how it is used throughout the test framework.
这篇关于如何将AST转换为JDT Java模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!