[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[news.eclipse.tools.jdt] Re: How to 'copy' MethodDeclaration from one CompilationUnit to another

Copying ast node from one AST to other:

MethodDeclaration method;
CompilationUnit other;
...
TypeDeclaration targetType = (TypeDeclaration) other.types.get(0);
targetType.bodyDeclarations().add(ASTNode.copySubtree(other.getAST(), method));


Werner Janjic wrote:
Hello!

I've got a problem in codeing a plugin. I've got a CompilationUnit created from Javacode in a file on the filesystem and can wonderfully traverse through it. Now I want to copy one method from this CompilationUnit to another CompilationUnit that I've got from the actual editor.

So I did - naively - the following:

[...]
MethodDeclaration orgMethod = methods[0];
((TypeDeclaration)editorCompUnit.types().get(0)).bodyDeclarations().add(orgMethod);


[...]

Unfortunately this returns an IllegalArgumentException and seeing the inner structure in the debugger I assume that this is due to the fact that orgMethod references its own AST and/or CPU and so the editor CPU can't handle that.

Now I'd like to know if there is a possibility to copy a method or type declaration from one CompilationUnit to another one, without haveing to code one million lines of code examining all of the original one and then storing it in the destination CPU. That seems pretty hard to me as I'm not so deep in AST/CPU programming. Is there some clone or copy option implemented?

Thank you in advance and I'd very much appreciate if you could provide me some code snippet with your answer. I've been trying it myself for days now and also searching the newsgroup and googleing didn't give me any idea.

Werner