Java code generation: how to modify an existing java file?

I have a .java src file that looks like this:

  class Test {

     public void foo () {
     }

 }

I would like to change foo () programmatically, in the sense, let's add sysout and do this:

  public void foo () {
     System.out.println ("hello world");
 }

Are there any known ways to do this by NOT directly editing the src file (RandomAccessFile)?

Several posts in StackOverflow relate to CodeModel and Eclipse JDT AST for code generation purposes. I see that they will help in generating the code from scratch and will not modify the existing code. Is there an API that allows you to modify existing code and that has an API as simple as CodeModel / Eclipse JDT AST? If not, what would be the best way to do this?

+4
source share
5 answers

You can use some byte code manipulation library, for example. JavaAssist See Section 4.2 Changing the body of a method in a tutorial for javaassist: http://www.csg.is.titech.ac.jp/~chiba/javassist/tutorial/tutorial2.html

+2
source

You can create code generation using JET templates or write custom annotation handlers. Note: in another note, the aspect-oriented framework implements this using a concept called code weaving when dot abbreviations are defined.

0
source

If you want to modify the source code file, you need a program conversion system. DMS Software Reengineering Toolkit - a program conversion tool that will read the source code, build compiler data structures (AST, symbol tables, flow graphs), allow you to apply source rewrites to the source of the code presented in the form of these structures, using the source templates for matching / replacement , and then regenerate a reliable source from the result.

DMS has a parser / prettyprinters for many languages, including Java, C, C ++, C #, COBOL, PHP, JavaScript, ...

0
source

If you insist on working with code generation, then you can create a Stub class for the Test class, and then the Test class extends the Stub class. Like this

class Test extends TestStub { 
@Override
public void foo() {
super.foo();
}
}
// Generated stub class
class TestStub {
public void foo() {
System.out.println("hello world");
}
}
0
source

If you are trying to edit the source code, not the byte, you can use the ASTRewrite class of the Eclipse JDT AST library to modify the existing Java source code file. You can read the documentation here. ASTRewrite

You can find some examples here. Using ASTRewrite

0
source

Source: https://habr.com/ru/post/1300877/


All Articles