Getting the qualified class name of generic type with Java 6 annotation processor

后端 未结 3 951
谎友^
谎友^ 2021-02-13 04:49

I am developing a small code generator using JDK 6\'s Annotation Processing API and am stuck trying to get the actual generic type of a field in the class. To be clearer, let\'

3条回答
  •  眼角桃花
    2021-02-13 05:50

    Looks like there are a couple of problems. One, the isAssignable() isnt working as expected. Second, in the above code you are trying to get the generic parameters of the Set type (T), rather than the variable declaration (Role).

    Nevertheless, the following code should demonstrate what you need:

    @SupportedAnnotationTypes({ "xxx.MyAnnotation" })
    @SupportedSourceVersion(SourceVersion.RELEASE_6)
    public class MongoDocumentAnnotationProcessor extends AbstractProcessor {
        @Override
        public synchronized void init(ProcessingEnvironment processingEnv) {
            super.init(processingEnv);
        }
    
        @Override
        public boolean process(Set annotations, RoundEnvironment roundEnv) {
            if (roundEnv.processingOver() || annotations.size() == 0) {
                return false;
            }
            for (Element element : roundEnv.getRootElements()) {
                if (element.getKind() == ElementKind.CLASS && isAnnotatedWithMongoDocument(element)) {
                    System.out.println("Running " + getClass().getSimpleName());
                    for (VariableElement variableElement : ElementFilter.fieldsIn(element.getEnclosedElements())) {
                        if(variableElement.asType() instanceof DeclaredType){
                            DeclaredType declaredType = (DeclaredType) variableElement.asType();
    
                            for (TypeMirror typeMirror : declaredType.getTypeArguments()) {
                                System.out.println(typeMirror.toString());
                            }
                        }
                    }
                }
            }
            return true;  //processed
        }
    
        private boolean isAnnotatedWithMongoDocument(Element element) {
            return element.getAnnotation(MyAnnotation.class) != null;
        }
    }
    

    This code should output:

    xxx.Role
    

提交回复
热议问题