Aman Sharma
Aman Sharma

Reputation: 287

API function `replace` doesn't replace a class with a CtClass instance

I am trying to execute the following piece of code.

System.out.println(originalElement);
System.out.println(uniqueParent);
((CtClass) originalElement).replace((CtClass) uniqueParent);

where

originalElement is

class Already {}

and uniqueParent is

class Already {
    class Klass {}
}

However, when I try to replace originalElement with uniqueParent, it doesn't work. I have tried the replace API with other elements such as CtMethod and it works there. I wanted to know if this is the intended behaviour with CtClass or is it supposed to be a bug?

Upvotes: 0

Views: 76

Answers (1)

Andrew
Andrew

Reputation: 96

To summarize a discussion about this at the Spoon forum, the problem here concerns the semantics of CtElement.replace. The meaning is not that the invocation target takes on the same state as its argument. It means that the AST model which used to contain the invocation's target object as a node now contains the argument object as a replacement.

When you used replace on a CtMethod, you probably checked the change with a parent element such as a CtClass and not that CtMethod itself. Similarly, you could use originalElement.getParent() after replacement to get a part of the current model to check the change. In this case, it will return a CtPackage that has a type element referenced by uniqueParent instead of originalElement.

Upvotes: 1

Related Questions