Eclipse Community Forums
Forum Search:

Search      Help    Register    Login    Home
Home » Language IDEs » Java Development Tools (JDT) » Insert Block from a different AST inside MethodDeclaration
Insert Block from a different AST inside MethodDeclaration [message #1768644] Thu, 20 July 2017 22:06 Go to next message
Cesar Orozco is currently offline Cesar OrozcoFriend
Messages: 1
Registered: July 2017
Junior Member
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:

md.setBody(block);

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?
Re: Insert Block from a different AST inside MethodDeclaration [message #1768713 is a reply to message #1768644] Fri, 21 July 2017 22:49 Go to previous message
Stephan Herrmann is currently offline Stephan HerrmannFriend
Messages: 1504
Registered: July 2009
Senior Member
Have a look at org.eclipse.jdt.core.dom.ASTNode.copySubtree(AST, ASTNode) / copySubtrees(AST, List)
Previous Topic:How to export a Programm, that relies on an external JAR and a 32 Bit DLL?
Next Topic:Causing a break into the debugger
Goto Forum:
  


Current Time: Thu Sep 21 12:33:30 GMT 2017

Powered by FUDForum. Page generated in 0.03365 seconds
.:: Contact :: Home ::.

Powered by: FUDforum 3.0.2.
Copyright ©2001-2010 FUDforum Bulletin Board Software