Created
April 24, 2020 11:48
-
-
Save mcherb/84324be8940737c7ad8ade03d84125f9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.sun.source.tree.ClassTree; | |
import com.sun.source.util.*; | |
import com.sun.tools.javac.api.BasicJavacTask; | |
import com.sun.tools.javac.code.Flags; | |
import com.sun.tools.javac.tree.JCTree; | |
import com.sun.tools.javac.tree.TreeMaker; | |
import com.sun.tools.javac.util.Context; | |
import com.sun.tools.javac.util.List; | |
import com.sun.tools.javac.util.Names; | |
public class SampleJavacPlugin implements Plugin { | |
@Override | |
public String getName() { | |
return "MyPlugin"; | |
} | |
@Override | |
public void init(JavacTask task, String... args) { | |
Context context = ((BasicJavacTask) task).getContext(); | |
task.addTaskListener(new TaskListener() { | |
@Override | |
public void started(TaskEvent e) { | |
} | |
@Override | |
public void finished(TaskEvent e) { | |
if (e.getKind() != TaskEvent.Kind.PARSE) { | |
return; | |
} | |
e.getCompilationUnit().accept(new TreeScanner<Void, Void>() { | |
@Override | |
public Void visitClass(ClassTree node, Void aVoid) { | |
TreeMaker maker = TreeMaker.instance(context); | |
Names symbolsTable = Names.instance(context); | |
JCTree.JCMethodDecl constructor = maker.MethodDef(maker.Modifiers(Flags.PUBLIC), | |
symbolsTable.init, | |
null, | |
List.nil(), // params | |
List.nil(), | |
List.nil(), | |
maker.Block(0, List.of(callSuper)), | |
null | |
); | |
JCTree.JCClassDecl myClass = maker | |
.at(((JCTree) node).pos) | |
.ClassDef(maker.Modifiers(Flags.PUBLIC | Flags.STATIC | Flags.FINAL), | |
symbolsTable.fromString("MyClass"), | |
List.nil(), | |
maker.Ident(symbolsTable.fromString("AnotherClass")), | |
List.nil(), | |
List.of(constructor) | |
); | |
((JCTree.JCClassDecl) node).defs = ((JCTree.JCClassDecl) node).defs.append(myClass); | |
return super.visitClass(node, aVoid); | |
} | |
}, null); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment