如何使用 JDT/AST 将代码片段添加到方法体 [英] How to add a code snippet to method body with JDT/AST

查看:34
本文介绍了如何使用 JDT/AST 将代码片段添加到方法体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 JDT/AST 生成 Java 源代码.我现在有 MethodDeclaration 并且想要将代码片段(来自其他来源)添加到方法主体.代码片段可以包含任何 Java 代码,甚至是语法无效的代码.我就是找不到这样做的方法.

I'm trying to generate Java source code with JDT/AST. I now have MethodDeclaration and want to add a code snippet (from another source) to the method body. The code snippet can contain any Java code, even syntactically invalid code. I just can't find the way to do this.

对于 JCodeModel,您将使用 JBlock#directStatement(String s) 方法.

With JCodeModel you would use JBlock#directStatement(String s) method.

有没有办法用 JDT/AST 做到这一点?

Is there a way to do this with JDT/AST?

推荐答案

由于您有一个用于应用程序其余部分的格式良好的树,并且您想在特定位置插入格式不正确的文本,所以您很漂亮使用标准的树节点插入机制无法做到这一点.

Since you have a well-formed tree for the rest of the application, and you want to insert non-well-formed text at a particular place, you pretty much can't do it with the standard tree node insertion mechanisms.

重要的是您为有效的程序文本生成文本,并将片段插入到正确的位置.在某处必须有一段将 AST 打印为文本的逻辑.您需要做的是要求将 AST 打印为文本,并在该过程的中间捕获它,在必要的精确点插入您的任意文本.

What matters is that you produce text for the valid program text with the fragment inserted in at at the right place. Somewhere in there must be a piece of logic that prints the AST as text. What you need to do is to ask that the AST be printed as text, and catch it in the middle of that process, at the precise point necessary, to insert your arbitrary text.

我们的 DMS 软件再工程工具包在它的漂亮打印机中有进入/退出打印节点挂钩,以允许这种事情发生.

Our DMS Software Reengineering Toolkit has enter/exit print-node hooks in its prettyprinter to allow this kind of thing to happen.

如果 JDT/AST 中不存在这样的东西,你可以尝试修改它的漂亮打印机来给你那个钩子.或者,您可以考虑通过添加另一个不属于标准集的树节点类型来修改 JDT/AST,该类型仅包含任意文本但充当方法节点.大概每个节点控制打印的内容;然后您可以为该树节点定义漂亮的打印,以使其输出其文本.

If such things don't exist in JDT/AST, you can try to modify its prettyprinter to give you that hook. Alternatively, you might consider modifying JDT/AST by adding a another tree node type that isn't part of the standard set, that simply holds arbitrary text but acts like a method node. Presumably each node controls what is printed; then you could define the prettyprinting for that tree node, to cause it to output its text.

最后一个非常棘手的解决方案:在任意文本所在的位置插入一个完全有效的 AST,在某处包含一个具有唯一名称的虚假标识符,例如 ZZZ.然后,将 AST 打印为字符串,并对该字符串进行后处理,以将包含唯一名称的虚假树替换为实际的用户文本.

A final really hacky solution: insert a perfectly valid AST where the arbitrary text will go, containing somewhere a bogus identifier with a unique name, e.g., ZZZ. Then, print the AST to a string, and post-process the string to replace the bogus trees containing the unique name with the actual user text.

这篇关于如何使用 JDT/AST 将代码片段添加到方法体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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