0

I'm trying to rename a variable using AST and JDT:

At this point I can retrieve the ASTnode of the wanted variable, and the getNodeType() method returns that the retrieved ASTnode is a "SimpleName", Here is the code snippet that I use to set the variable name:

ASTNode an=nf.getCoveringNode();
SimpleName sn= ast.newSimpleName("rename_type");
 
if (an.getParent() instanceof SimpleType) {
    SimpleType st= (SimpleType)an.getParent(); 
    Name n=ast.newName("newname");
    st.setName(n);
}

Now it throws:

java.lang.IllegalArgumentException: AST node cannot be modified.

Have you an idea how can I solve this?

İsmail Y.
  • 3,579
  • 5
  • 21
  • 29
  • Cite from `SimpleType` javadoc: `Type node for a named class type, a named interface type, or a type variable.` So, first of all, you trying to change some type name, not variable name. Do [this answer](https://stackoverflow.com/a/13054545/882813) is what you looking for? – user882813 Apr 25 '21 at 16:21
  • Thanks for your answer. Yes I'm trying to change a type name. I found the post you shared but it is not really what I look for, I have to use jdt AST API only – zohrakaouter Apr 26 '21 at 04:46
  • You probably need an `ASTRewriter`. [Vogella's article](https://www.vogella.com/tutorials/EclipseJDT/article.html#adding-imports-with-astrewrite) can be used as a starting point. – user882813 Apr 26 '21 at 11:49
  • I read the vogella tuto also, I tried to use the rewriter but the exception appears before the compiler achieve the rewriter ( in the `setName method call) – zohrakaouter Apr 26 '21 at 12:29

0 Answers0