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?
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
replaceon aCtMethod, you probably checked the change with a parent element such as aCtClassand not thatCtMethoditself. Similarly, you could useoriginalElement.getParent()after replacement to get a part of the current model to check the change. In this case, it will return aCtPackagethat has a type element referenced byuniqueParentinstead oforiginalElement.