I have just started using annotation processing and trying to inject the value on the field annotated with my annotation . Since yesterday I am facing this error message: Compilation failure
I have tried to research and fix but unable to avoid this error here is my CustomValueProcessor.java
class and my annotation:
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomValue {
String value(); // This attribute will hold the property value
}
import com.google.auto.service.AutoService;
import report.configurations.PropertyLoader;
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import javax.tools.Diagnostic;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.Set;
@SupportedAnnotationTypes("report.annotations.CustomValue")
@SupportedSourceVersion(SourceVersion.RELEASE_17)
@AutoService(javax.annotation.processing.Processor.class)
public class CustomValueProcessor extends AbstractProcessor {
private Messager messager;
private final Map<String, String> PropMap = PropertyLoader.parsePropertiesFile();
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
messager = processingEnv.getMessager();
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
for (TypeElement annotation : annotations) {
for (Element element : roundEnv.getElementsAnnotatedWith(annotation)) {
if (element.getKind() == ElementKind.FIELD) {
CustomValue annotationValue = element.getAnnotation(CustomValue.class);
String newParaName = annotationValue.value().substring(2, annotationValue.value().length() - 1);
String propertyValue = PropMap.get(newParaName);
//messager.printMessage(Diagnostic.Kind.ERROR, propertyValue);
VariableElement fieldElement = (VariableElement) element;
String fieldName = fieldElement.getSimpleName().toString();
//messager.printMessage(Diagnostic.Kind.ERROR, fieldName);
// Get the class type from the TypeElement
TypeElement enclosingClass = (TypeElement) fieldElement.getEnclosingElement();
TypeMirror classType = enclosingClass.asType();
//messager.printMessage(Diagnostic.Kind.ERROR, classType.toString());
// Assuming PdfService is in the same package as enclosingClass
Class<?> clazz = enclosingClass.getClass();
// Get the field
try {
Field field = clazz.getDeclaredField(fieldName);
//messager.printMessage(Diagnostic.Kind.ERROR,field.toString());
field.setAccessible(true);
// Set the value of the field
field.set(null, propertyValue); // Pass an object instance instead of null if the field is non-static
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
}
}
return false;
}
return false;
}
}
Please suggest/advice what I am doing wrong.