INRIA / spoon

Spoon is a metaprogramming library to analyze and transform Java source code. :spoon: is made with :heart:, :beers: and :sparkles:. It parses source files to build a well-designed AST with powerful analysis and transformation API.
http://spoon.gforge.inria.fr/
Other
1.75k stars 349 forks source link

Replacing an invocation #670

Closed kribo852 closed 8 years ago

kribo852 commented 8 years ago

Hi, I am trying to replace all method invocations to a certain method with a static method from another class. As it is now, the replacement looks correct after a transformation, but the new class is not imported to file where the invocation is made. This even though the new class should have been loaded by Spoon. What is the correct/best way of replacing an invocation with a new one that is static? Regards, Kristoffer.

tdurieux commented 8 years ago

did you use snippet?

kribo852 commented 8 years ago

no, I think we tried to make a CtTypeReference and then use that to make the invocation, even though I might have to come back to you with the exact details tomorrow. We have done method invocations in a similar way before and I suspect that it is because the method is static that we don't get the import to work.

tdurieux commented 8 years ago

Here the method that I use to create a static method call:

    public static CtInvocation createStaticCall(Factory factory, Class<?> clazz, String methodName, CtExpression...arguments) {
        CtTypeReference<?> classReference = factory.Type().createReference(clazz);
        CtExecutableReference execRef = factory.Core().createExecutableReference();
        execRef.setDeclaringType(classReference);
        execRef.setSimpleName(methodName);
        execRef.setStatic(true);

        CtTypeAccess typeAccess = factory.Core().createTypeAccess();
        typeAccess.setType(classReference);
        typeAccess.setAccessedType(classReference);
        return factory.Code().createInvocation(typeAccess, execRef, arguments);
    }
kribo852 commented 8 years ago

Thanks, I found another way, but this seems like a better soloution. I might try it later.