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

后端 未结 3 938
谎友^
谎友^ 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:47

    All the other answers, while having lots of good points. Don't really show you the problem you have and it's solution.

    The problem in your code is here

    TypeElement collectionType = elementUtils.getTypeElement("java.util.Collection");
    if (typeUtils.isAssignable(typeElement.asType(), collectionType.asType())) {
    ...
    

    Your type is not extending java.util.Collection but rather java.util.Collection<*>. Let's rewrite the above block to reflect this:

    WildcardType WILDCARD_TYPE_NULL = this.typeUtils.getWildcardType(null, null);
    final TypeElement collectionTypeElement = this.elementUtils.getTypeElement(Collection.class.getName());
    TypeMirror[] typex = {WILDCARD_TYPE_NULL};
    DeclaredType collectionType=this.typeUtils.getDeclaredType(collectionTypeElement, typex);
    if (typeUtils.isAssignable(typeElement.asType(), collectionType)){ 
     ...
    

    That should make it work

提交回复
热议问题