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 352 forks source link

Ho to add variable in class using spoon #4579

Open abhinaswale opened 2 years ago

abhinaswale commented 2 years ago

I want to remove some code from the class, identify the classname from it and create a variable for same class. I am able to do the first 2 parts but not able to add the code in CtClass as a variable. Please help.

Current code:

public class BankProcessor {
    public Collection getAccountInformation(String customerId){
    Context context = new InitialContext();
    ArrayList accountBeanList = new ArrayList();
        CustomerHomeLocal customerHome = (CustomerHomeLocal)context.lookup(CustomerHomeLocal.JNDI_NAME);
        CustomerLocal customer = customerHome.findByPrimaryKey(customerId);
        Iterator accountIterator = customer.getAccounts().iterator();               
        }
}

Expected Code

public class BankProcessor {
    @Autowired
    private CustomerHomeLocal customerHome;

    public Collection getAccountInformation(String customerId){
        ArrayList accountBeanList = new ArrayList();
        CustomerLocal customer = customerHome.findByPrimaryKey(customerId);
        Iterator accountIterator = customer.getAccounts().iterator();           
        }
}

I have tried creating codeSnippet from

classfactory.Code().createCodeSnippetStatement("CustomerHomeLocal customerHome;")

but not able to add it to

CtClass

MartinWitt commented 2 years ago

I'm unsure what transformation you try to accomplish. You want to convert CustomerHomeLocal customerHome = (CustomerHomeLocal)context.lookup(CustomerHomeLocal.JNDI_NAME); to a field with an annotation

    @Autowired
    private CustomerHomeLocal customerHome;

? If this is your goal you want to create a new CtField(see https://spoon.gforge.inria.fr/mvnsites/spoon-core/apidocs/spoon/reflect/declaration/CtField.html) and add it to the CtClass with addField.