Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing java code and adding methods with AST (JDT Eclipse)

I have a .java file which contains a class. I want to add a method to that class but I can't find a real useful "HOWTO" or examples around. I'm using Eclipse and its JDT plugin for AST. I tried a code that creates an ICompilationUnit from a project

IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject("ProjName");
IJavaProject javaProject = JavaCore.create(project);
IPackageFragment package1 = javaProject.getPackageFragments()[0];
ICompilationUnit unit = package1.getCompilationUnits()[0];

then add a method with astrewrite. But it seems to work only if I run all as a Plugin Project and not a simple Java Application. I need to write an application in java that "simply" parse a java file and adds method to its class. What I supposed to do is: 1) Create an ICompilationUnit directly form the .java file I want to parse (eventually located in my own project's directory) 2) Using another way

Both case I can't go further. Anyone can help me?

like image 447
user1847118 Avatar asked Jul 17 '26 04:07

user1847118


1 Answers

When you need to make a change by adding something to the compilation unit, you will have to use the functions provided by CompilationUnit to create new nodes.

To add a method to "unit" you will have to :

  • Create a MethodDeclaration node using your compilation unit :

MethodDeclaration md = unit.getAST().newMethodDeclaration();

  • Customize this method declaration to your requirements :

md.setName( unit.getAST().newSimpleName( "newMethod" ) ); md.setBody( unit.getAST().newBlock() );

this will produce : void newMethod() {}

  • Obtain the TypeBinding from "unit" :

TypeDeclaration typeDeclaration = ( TypeDeclaration )unit.types().get( 0 );

  • Add your newly created MethodDeclaration to the body declarations :

typeDeclaration.bodyDeclarations().add( md );

There's a method called getMethods() on TypeDeclaration but it doesn't return a live list of MethodDeclarations, therefore you can't modify that directly.

like image 77
alextsil Avatar answered Jul 18 '26 19:07

alextsil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!