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?
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 :
MethodDeclaration md = unit.getAST().newMethodDeclaration();
md.setName( unit.getAST().newSimpleName( "newMethod" ) );
md.setBody( unit.getAST().newBlock() );
this will produce : void newMethod() {}
TypeDeclaration typeDeclaration = ( TypeDeclaration )unit.types().get( 0 );
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With