An abstract syntax tree (AST). http://home.a00.itscom.net/hatada/c-tips/ast/ast01.html
Analyze the source code and generate a tree with each node as a leaf.
JavaPerser https://github.com/javaparser/javaparser/wiki
If you use the library of com.sun.tools.javac.model, you can change the intermediate AST at compile time ...? ??
In order to parse the source code, parse it with the following code and convert it to the CompilationUnit type. You can specify InputSteream, File, etc. in this argument.
JavaParser.parse([source]);
Once converted to CompilationUnit, you can get the object that represents each node, so you can modify it from there.
The nodes that could be obtained directly from the Compilation Unit are:
Perhaps if you want to process the node in Class (or Interface), get ClassOrInterfaceDeclaration once and modify it.
targetclass.getMethodsByName("testMethod1")
Now you can get a list of node MethodDeclarations that represent methods with the name "testMethod1". (If there is the same name, it will be added to the list accordingly)
Modifier refers to private or something like that
Also, if you want to get a Method with arguments.
//You can get a Method with String and int as arguments with the name methodName.
ClassOrInterfaceDeclaration.getMethodsBySignature(String new methodName, new String[] {"String","int"});
If you call remove () as it is, it disappears.
Call setName (String name). You can also assign using a SimpleName object
Change the initialization with setInitializer of VariableDeclarator. The argument is of Expression type, which can be created by JavaParser.parseExpression.
VariableDeclarator.setInitializer(JavaParser.parseExpression(content));
Use ClassOrInterfaceDeclaration as before. You can call add *** for this object to get the object that represents that node as it is added.
//private ScanSize[] aaa;To add
FieldDeclaration field = targetclass.addField(ScanSize[].class, "aaa", Modifier.PRIVATE);
If you put the VariableDeclarator created elsewhere in setVariable () of this field object, it will be entered as it is.
Maybe the method can go as well, maybe.
Get your own source and parse
Path selfSource = Paths.get("[Source Path]");
By doing this, you can get arbitrary declarations etc., so all you have to do is plunge into another file
Detailed article about Java Parser https://qiita.com/opengl-8080/items/50ddee7d635c7baee0ab#%E5%8F%82%E8%80%83
AST conversion in annotation processor --change variable type at compile time with reference to Lombok http://fits.hatenablog.com/entry/2015/01/17/172651
Recommended Posts