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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With