如何以编程方式从Java源代码中的类中提取方法体?
我想从 Java 源代码中提取方法体。 假设我有以下代码:
public class A{
public void print(){
System.out.println("Print This thing");
System.out.println("Print This thing");
System.out.println("Print This thing");
}
}
我的目标不是提取方法名称(在本例中为 print),而是提取方法的 bode 方法(在本例中是 print 方法内的三个 print 语句)。谁能建议我该怎么做?他们有任何图书馆可以这样做吗?
I want to extract method body from a Java Source Code.
Suppose I have the following code:
public class A{
public void print(){
System.out.println("Print This thing");
System.out.println("Print This thing");
System.out.println("Print This thing");
}
}
My objective is not to extract the method name (in this case print) but also the bode of the
method(In this case the three print statement inside the print method). Can anyone suggest how can I do so? Is their any library available for doing so.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您谈论的是操作源代码,所有 IDE 都具有某种程度的重构支持,允许您选择一行或多行代码并创建由这些行组成的方法。
如果您想以编程方式执行此操作,则需要解析源文件。您可以编写词法分析器和解析器,但这需要大量工作,除非您正在构建 IDE。您可能想看看 注释处理。这可能还不够,除非您还使用 编译器树 API。但请注意,当您去那里时,您将冒险离开“随处运行”路径并进入“特定于实现”的领域。
如果您希望在运行时进行操作,请查看 BCEL 或 ASM 和 Java 代理。
If you're talking about manipulating source code, all of the IDEs have some degree of refactoring support that will allow you to select one or more lines of code and create a method consisting of those lines.
If you want to do that programatically, you'll need to parse the source file. You could write a lexer and parser, but that's a lot of work unless you're building an IDE. You may want to take a look at Annotation processing. That probably won't go far enough unless you also use a Compiler Tree API. Note, however that when you go there you're venturing off the "run anywhere" path and entering "implementation specific" land.
If you're looking to manipulate things at runtime, then take a look at BCEL or ASM and Java Agents.
这是我看到的检索方法名称的一种 hack 方式:
具有更强 Java 能力的人可能能够提供一种更简洁的方法,并且还提供一种检索方法主体的方法。
Here is a hack-ish way I have seen the method name retrieved:
Someone with stronger Java-fu might be able to give a cleaner approach and also provide a way to retrieve the body of the method.
Eclipse 中的 Alt-Shift-I 将尝试内联方法调用(将光标放在方法调用上)。
Alt-Shift-I in eclipse will attempt to inline the method call (with your cursor on the method call).