如何将 AST 转换为 JDT Java 模型 [英] How to convert AST to JDT Java model

查看:34
本文介绍了如何将 AST 转换为 JDT Java 模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为使用 JDT 的 IType 和 IMethod 接口的插件编写单元测试.要编写单元测试,我需要实例化这样的接口.回答这个问题展示了如何创建 AST 模型,但我没有知道如何将其转换为Java模型吗?

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?

我的代码如下:

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 的实例,以便我可以访问 IMethodIType 对象.

So I have an instance of CompilationUnit, but I need an instance of ICompilationUInit, so I can get access to IMethod and IType objects.

推荐答案

这真的不可能.ICompilationUnits 是 java 模型的一部分,这意味着它是某个 Java 项目的一部分,并且具有完整的类路径、包、包根等.您所做的只是创建一个解析一些未连接到任何 java 项目的文本树.

This is not really possible. ICompilationUnits 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.

如果您可以更具体地说明您的目标是什么,那么您可能并不真正需要任何 IType 和 IMethod 实例.

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.

或者,如果您确实需要这些类型的实例,那么您将需要生成 IProjects,向其中添加 java 特性,然后用文件填充它.最好的办法是了解 JDT 测试基础架构的工作原理.

Or, if you really do need instances of these types, then you will need to generate IProjects, add a java nature to it, and then populate it with files. Your best bet is to see how the JDT test infrastructure works.

看看这个文件: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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆