Created
April 18, 2020 14:28
-
-
Save mcherb/6eed3e8f7919fa31beced33b8a54d297 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.JCClassDecl myClass = maker | |
.at(((JCTree) node).pos) | |
.ClassDef(maker.Modifiers(Flags.PUBLIC | Flags.STATIC | Flags.FINAL), | |
symbolsTable.fromString("MyClass"), | |
List.nil(), | |
null, // Here | |
List.nil(), | |
List.nil() | |
); | |
((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