How to add a method source to an existing java file with JDT?
I'm writing a simple eclipse plugin, which is a code generator. User can choose an existing method, then generate a new test method in corresponding test file, with JDT.
Assume the test files is already existed, and it's content is:
public class UserTest extends TestCase {
public void setUp(){}
public void tearDown(){}
public void testCtor(){}
}
Now I have generate some test code:
/** complex javadoc */
public void testSetName() {
....
// complex logic
}
What I want to do is to append it to the existing UserTest
. I have to code:
String sourceContent = FileUtils.readFileToString("UserTest.java", "UTF-8");
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setSource(content.toCharArray());
CompilationUnit testUnit = (CompilationUnit) parser.createAST(null);
String newTestCode = "public void testSetName() { .... }";
// get the first type
final List<TypeDeclaration> list = new ArrayList<TypeDeclaration>();
testUnit .accept(new ASTVisitor() {
@Override
public boolean visit(TypeDeclaration node) {
list.add(node);
return false;
}
});
TypeDeclaration type = list.get(0);
type.insertMethod(newTestCode); // ! no this method: insertMethod
But there is no such a method insertMethod
.
I know two options now:
- Do not use
jdt
, just to insert the new code to the test file, before last}
- use
testUnit.getAST().newMethodDeclaration()
to create a method, then update it.
But I don't like these two options, I hope there is something like insertMethod
, which can let me append some text to the test compilation unit, or convert the test code to a MethodDeclaration, then append to the test compilatio开发者_如何学运维n unit.
UPDATE
I see nonty's answer, and found there are two CompilationUnit
in jdt. One is org.eclipse.jdt.internal.core.CompilationUnit
, another is org.eclipse.jdt.core.dom.CompilationUnit
. I used the second one, and nonty used the first one.
I need to supplement my question: At first I want to create a eclipse-plugin, but later I found it hard to create a complex UI by swt, so I decided to create a web app to generate the code. I copied those jdt jars from eclipse, so I can just use org.eclipse.jdt.core.dom.CompilationUnit
.
Is there a way to use org.eclipse.jdt.internal.core.CompilationUnit
outside eclipse?
What is wrong with
...
String newTestCode = "public void testSetName() { .... }";
IProgressMonitor monitor = new NullProgressMonitor();
IMethod method = testUnit.getTypes[0].createMethod(newTestCode, null, false, monitor);
You can even specify where to add the new method and whether to "overwrite" any exiting method.
JavaCore has a method to create a CompilationUnit from a given IFile.
IFile file;
JavaCore.createCompilationUnitFrom(file);
精彩评论