Search in sources :

Example 1 with CloneHelper

use of spoon.support.visitor.equals.CloneHelper in project spoon by INRIA.

the class CloneTest method testCloneListener.

@Test
public void testCloneListener() throws Exception {
    // contract: it is possible to extend the cloning behavior
    // in this example extension, a listener of cloning process gets access to origin node and cloned node
    // we check the contract with some complicated class as target of cloning
    Factory factory = ModelUtils.build(new File("./src/main/java/spoon/reflect/visitor/DefaultJavaPrettyPrinter.java"));
    CtType<?> cloneSource = factory.Type().get(DefaultJavaPrettyPrinter.class);
    class CloneListener extends CloneHelper {

        Map<CtElement, CtElement> sourceToTarget = new IdentityHashMap<>();

        @Override
        public <T extends CtElement> T clone(T source) {
            if (source == null) {
                return null;
            }
            T target = super.clone(source);
            onCloned(source, target);
            return target;
        }

        private void onCloned(CtElement source, CtElement target) {
            CtElement previousTarget = sourceToTarget.put(source, target);
            assertNull(previousTarget);
        }
    }
    CloneListener cl = new CloneListener();
    CtType<?> cloneTarget = cl.clone(cloneSource);
    cloneSource.filterChildren(null).forEach(sourceElement -> {
        // contract: there exists cloned target for each visitable element
        CtElement targetElement = cl.sourceToTarget.remove(sourceElement);
        assertNotNull("Missing target for sourceElement\n" + sourceElement, targetElement);
        assertEquals("Source and Target are not equal", sourceElement, targetElement);
    });
    // contract: each visitable elements was cloned exactly once.  No more no less.
    assertTrue(cl.sourceToTarget.isEmpty());
}
Also used : CloneHelper(spoon.support.visitor.equals.CloneHelper) CtElement(spoon.reflect.declaration.CtElement) Factory(spoon.reflect.factory.Factory) File(java.io.File) Map(java.util.Map) IdentityHashMap(java.util.IdentityHashMap) Test(org.junit.Test)

Aggregations

File (java.io.File)1 IdentityHashMap (java.util.IdentityHashMap)1 Map (java.util.Map)1 Test (org.junit.Test)1 CtElement (spoon.reflect.declaration.CtElement)1 Factory (spoon.reflect.factory.Factory)1 CloneHelper (spoon.support.visitor.equals.CloneHelper)1