INRIA / INRIA/spoon

How can I add code to a constructor?

Open
#4,575 3 comments 0 reactions 0 assignees View on GitHub
Dominant language
Java
Stars
2k
Forks
392
Avg merge
11h 24m
Merged PRs (30d)
36

Description

I'm having trouble adding code to a constructor. I was able to get some of the examples working in the example repo but couldn't figure out how to get this to work. What I want to do is:

For every `@Find` annotation I want to initialize the field inside the constructor that takes a parameter of type `MyObject`. The processor runs fine but the output is not there. nothing is outputed and no errors either.

My class:

```java
public class SomeClass extends SomeBaseClass {
@Find(foo = "bar")
SomeInterface x;

public SomeClass(MyObject obj) {
super(obj);
// I want to add initialization code here
}
}
```

And here is my processor:

```java
public class FindProcessor extends AbstractAnnotationProcessor> {
@Override
public void process(Find annotation, CtAnnotation element) {
// get variable name of the field that is annotated
var variableName = element.getParent(CtField.class).getSimpleName();

// create a snippet that initializes the field
CtCodeSnippetStatement snippet = getFactory().Core().createCodeSnippetStatement();
final String value = String.format("%s = MyFactory.create('%s')", variableName, annotation.foo());
snippet.setValue(value);

// get the class that the field is in
var parentClass = element.getParent(CtClass.class);

// maybe this is the problem?
// Not sure how else to get CtTypeReference to pass to getConstructor
var constructorParamType = parentClass.getReferencedTypes()
.stream()
.filter(x -> x.getQualifiedName().equals("com.myPackage.foo.MyObject"))
.findFirst()
.orElse(null);

// get the constructor that has a parameter of type com.myPackage.foo.MyObject
var constructor = parentClass.getConstructor(constructorParamType);

// add the snipped at the end of the constructor
constructor.getBody().insertEnd(snippet);
}
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.