问题
I was wondering if there is already a library to programmatically write a java class or method?
I am looking for libraries capable of writing new source code into existing files or extend files that already exist.
回答1:
Look into Eclipse JDT.
The Eclipse Java Development Tools (JDT) provide APIs to access and manipulate Java source code. It allows to access the existing projects in the workspace, create new projects and modify and read existing projects.
More specifically, you can create new Java elements e.g. projects, packages, classes using the Java Model API and then you can then create/modify contents of a type e.g. methods, statements via the AST (Abstract Syntax Tree)
You should see this article and also this tutorial.
回答2:
What you want is a program transformation system. Such tools read source code, build compiler data structures, let you code custom analyzers/transformations on those structures, and the spit out the source code that corresponds to compiler data structures; this gives you the "extend a file" capability. New code generation is accomplished by simply building the corresponding compiler data structures and then spitting out the corresponding code.
Our DMS Software Reengineering Toolkit is precisely such a system. It reads Java source, builds compiler data structures such as abstract syntax trees and symbol tables (it can build control flow graphs, call trees and data flows), lets you climb over these structures with procedural code, or write "source-to-source transformations" using the surface syntax of the target (in this case, Java) language, and then it can generate valid java code from these compiler data structures.
It has been used to implement a variety of Java analysis and transformation tools that you can see that the web site. The easiest one to understand is using program transformations to build a test coverage tool.
回答3:
The Apache Byte Code Engineering Library is very exciting to work with, though it's not the same as Java source-code manipulation.
However, you can use it to:
- inspect existing bytecode;
- modify existing bytecode;
- generate bytecode and run it.
Custom languages targeting the JVM (like Scala) often use byte-code manipulation to generate Java classes.
With some effort you can extend this library to do "meta-programming": writing Java source-code at runtime.
来源:https://stackoverflow.com/questions/5243875/programmatically-writing-java