I have a JDT AST MethodDeclaration difined like this:
MethodDeclaration md = ast.newMethodDeclaration();
SimpleName sn = ast.newSimpleName("myMethod");
md.setName(sn);
Then I created an Block based on a String that contains some Java code, like this:
String body = "int a = 1;\n int b = 2;\n return (a + b);";
ASTParser parser = ASTParser.newParser(AST.JLS8);
parser.setSource(body.toCharArray());
parser.setKind(ASTParser.K_STATEMENTS);
Block block = (Block) parser.createAST(null);
Now I'm trying to insert the Block into the MethodDeclaration object as the body of the method so at the end it should look likt this:
void myMethod(){
int a = 1;
int b = 2;
return (a + b);
}
But when I do this:
It fails with this exception:
Caused by: java.lang.IllegalArgumentException
at org.eclipse.jdt.core.dom.ASTNode.checkNewChild(ASTNode.java:2083)
at org.eclipse.jdt.core.dom.ASTNode$NodeList.add(ASTNode.java:1417)
at java.util.AbstractList.add(AbstractList.java:119)
at java.util.AbstractCollection.addAll(AbstractCollection.java:355)
And debugged the ASTNode.checkNewChild and I can see this comment there:
// new child is from a different AST
Looks like it fails because the block object does not come from the same AST as the MethodDeclaration object, then how can I add this block?