Java Code Examples for javax.lang.model.element.TypeElement#getSuperclass()

The following examples show how to use javax.lang.model.element.TypeElement#getSuperclass() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TargetValidator.java    From Mixin with MIT License 6 votes vote down vote up
private boolean validateSuperClassRecursive(TypeMirror targetType, TypeMirror superClass) {
    if (!(targetType instanceof DeclaredType)) {
        return false;
    }
    
    if (TypeUtils.isAssignable(this.processingEnv, targetType, superClass)) {
        return true;
    }
    
    TypeElement targetElement = (TypeElement)((DeclaredType)targetType).asElement();
    TypeMirror targetSuper = targetElement.getSuperclass();
    if (targetSuper.getKind() == TypeKind.NONE) {
        return false;
    }
    
    if (this.checkMixinsFor(targetSuper, superClass)) {
        return true;
    }
    
    return this.validateSuperClassRecursive(targetSuper, superClass);
}
 
Example 2
Source File: TypeModeler.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public static TypeElement getDeclaringClassMethod(TypeElement theClass, String methodName, TypeMirror[] args) {

        TypeElement retClass = null;
        if (theClass.getKind().equals(ElementKind.CLASS)) {
            TypeMirror superClass = theClass.getSuperclass();
            if (!superClass.getKind().equals(TypeKind.NONE))
                retClass = getDeclaringClassMethod(superClass, methodName, args);
        }
        if (retClass == null) {
            for (TypeMirror interfaceType : theClass.getInterfaces()) {
                retClass = getDeclaringClassMethod(interfaceType, methodName, args);
            }
        }
        if (retClass == null) {
            Collection<? extends ExecutableElement> methods = ElementFilter.methodsIn(theClass.getEnclosedElements());
            for (ExecutableElement method : methods) {
                if (method.getSimpleName().toString().equals(methodName)) {
                    retClass = theClass;
                    break;
                }
            }
        }
        return retClass;
    }
 
Example 3
Source File: GeneratorUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static List<TypeElement> getAllClasses(TypeElement of) {
    List<TypeElement> result = new ArrayList<>();
    TypeMirror sup = of.getSuperclass();
    TypeElement te = sup.getKind() == TypeKind.DECLARED ? (TypeElement) ((DeclaredType)sup).asElement() : null;
    
    result.add(of);
    
    if (te != null) {
        result.addAll(getAllClasses(te));
    } else {
        if (ERR.isLoggable(ErrorManager.INFORMATIONAL)) {
            ERR.log(ErrorManager.INFORMATIONAL, "te=null, t=" + of);
        }
    }
    
    return result;
}
 
Example 4
Source File: ExportNonAccessibleElement.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public Boolean visitType(TypeElement arg0, Void arg1) {
    for (TypeParameterElement e : arg0.getTypeParameters()) {
        if (stop) {
            return false;
        }
        
        for (TypeMirror b : e.getBounds()) {
            if (stop) {
                return false;
            }
            
            if (b.accept(this, arg1)) {
                return true;
            }
        }
    }

    TypeMirror superclass = arg0.getSuperclass();
    if (superclass.getKind() == TypeKind.DECLARED) {
        if (!((DeclaredType) superclass).asElement().getKind().isInterface()) {
            return false;
        }
    }

    return superclass.accept(this, arg1);
}
 
Example 5
Source File: Utils.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Given a class, return the closest visible super class.
 *
 * @param te the TypeElement to be interrogated
 * @return the closest visible super class.  Return null if it cannot
 *         be found..
 */
public TypeMirror getFirstVisibleSuperClass(TypeElement te) {
    TypeMirror superType = te.getSuperclass();
    if (isNoType(superType)) {
        superType = getObjectType();
    }
    TypeElement superClass = asTypeElement(superType);
    // skip "hidden" classes
    while ((superClass != null && isHidden(superClass))
            || (superClass != null &&  !isPublic(superClass) && !isLinkable(superClass))) {
        TypeMirror supersuperType = superClass.getSuperclass();
        TypeElement supersuperClass = asTypeElement(supersuperType);
        if (supersuperClass == null
                || supersuperClass.getQualifiedName().equals(superClass.getQualifiedName())) {
            break;
        }
        superType = supersuperType;
        superClass = supersuperClass;
    }
    if (te.asType().equals(superType)) {
        return null;
    }
    return superType;
}
 
Example 6
Source File: SignatureFactory.java    From buck with Apache License 2.0 6 votes vote down vote up
@Override
public Void visitType(TypeElement element, SignatureVisitor visitor) {
  if (!signatureRequired(element)) {
    return null;
  }

  for (TypeParameterElement typeParameterElement : element.getTypeParameters()) {
    typeParameterElement.accept(this, visitor);
  }

  TypeMirror superclass = element.getSuperclass();
  if (superclass.getKind() != TypeKind.NONE) {
    superclass.accept(typeVisitorAdapter, visitor.visitSuperclass());
  } else {
    // Interface type; implicit superclass of Object
    SignatureVisitor superclassVisitor = visitor.visitSuperclass();
    superclassVisitor.visitClassType("java/lang/Object");
    superclassVisitor.visitEnd();
  }

  for (TypeMirror interfaceType : element.getInterfaces()) {
    interfaceType.accept(typeVisitorAdapter, visitor.visitInterface());
  }

  return null;
}
 
Example 7
Source File: TypeModeler.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static TypeElement getDeclaringClassMethod(TypeElement theClass, String methodName, TypeMirror[] args) {

        TypeElement retClass = null;
        if (theClass.getKind().equals(ElementKind.CLASS)) {
            TypeMirror superClass = theClass.getSuperclass();
            if (!superClass.getKind().equals(TypeKind.NONE))
                retClass = getDeclaringClassMethod(superClass, methodName, args);
        }
        if (retClass == null) {
            for (TypeMirror interfaceType : theClass.getInterfaces()) {
                retClass = getDeclaringClassMethod(interfaceType, methodName, args);
            }
        }
        if (retClass == null) {
            Collection<? extends ExecutableElement> methods = ElementFilter.methodsIn(theClass.getEnclosedElements());
            for (ExecutableElement method : methods) {
                if (method.getSimpleName().toString().equals(methodName)) {
                    retClass = theClass;
                    break;
                }
            }
        }
        return retClass;
    }
 
Example 8
Source File: EasyMVPProcessor.java    From EasyMVP with Apache License 2.0 6 votes vote down vote up
private String findViewTypeOfPresenter(TypeElement presenterElement) {
    TypeElement currentClass = presenterElement;
    while (currentClass != null) {
        if (currentClass.getSuperclass() instanceof DeclaredType) {
            List<? extends TypeMirror> superClassParameters =
                    ((DeclaredType) currentClass.getSuperclass()).getTypeArguments();

            if (superClassParameters.size() == 1) {
                String type = superClassParameters.get(0).toString();
                if (!"V".equals(type)) return type;
            }
        }
        currentClass = getSuperClass(currentClass);
    }
    return "";
}
 
Example 9
Source File: ShortcutProcessor.java    From shortbread with Apache License 2.0 6 votes vote down vote up
private boolean isSubtypeOfActivity(TypeMirror typeMirror) {
    if ("android.app.Activity".equals(typeMirror.toString())) {
        return true;
    }

    if (typeMirror.getKind() != TypeKind.DECLARED) {
        return false;
    }

    DeclaredType declaredType = (DeclaredType) typeMirror;
    Element element = declaredType.asElement();
    if (!(element instanceof TypeElement)) {
        return false;
    }

    TypeElement typeElement = (TypeElement) element;
    TypeMirror superType = typeElement.getSuperclass();
    return isSubtypeOfActivity(superType);
}
 
Example 10
Source File: IntentLifeProcessor.java    From IntentLife with Apache License 2.0 6 votes vote down vote up
/**
 * Find all parent classes and interfaces from current class.
 * It is be deprecated,now.
 */
@Deprecated
private boolean isParcelable(TypeElement currentClass) {

    if (null == currentClass) {
        return false;
    }
    for (TypeMirror mirror : currentClass.getInterfaces()) {
        if (mirror.toString().equals("android.os.Parcelable")) {
            return true;
        }
    }
    final TypeMirror superClassType = currentClass.getSuperclass();
    if (superClassType.getKind() == TypeKind.NONE) {
        // "TypeKind.NONE" meanings currentClass=java.lang.Object
        return false;
    }
    final TypeElement superClass = (TypeElement) mTypes.asElement(superClassType);
    return isParcelable(superClass);
}
 
Example 11
Source File: TargetValidator.java    From Mixin with MIT License 5 votes vote down vote up
private void validateClassMixin(TypeElement mixin, Collection<TypeHandle> targets) {
    TypeMirror superClass = mixin.getSuperclass();
    
    for (TypeHandle target : targets) {
        TypeMirror targetType = target.getType();
        if (targetType != null && !this.validateSuperClass(targetType, superClass)) {
            this.error("Superclass " + superClass + " of " + mixin + " was not found in the hierarchy of target class " + targetType, mixin);
        }
    }
}
 
Example 12
Source File: TreeBackedTypeElementTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetSuperclassOfEnumIsEnumWithArgs() throws IOException {
  compile("enum Foo { }");

  TypeElement fooElement = elements.getTypeElement("Foo");
  DeclaredType superclass = (DeclaredType) fooElement.getSuperclass();

  TypeElement enumElement = elements.getTypeElement("java.lang.Enum");
  TypeMirror expectedSuperclass = types.getDeclaredType(enumElement, fooElement.asType());

  assertSameType(expectedSuperclass, superclass);
}
 
Example 13
Source File: ApNavigator.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public TypeElement getSuperClass(TypeElement typeElement) {
    if (typeElement.getKind().equals(ElementKind.CLASS)) {
        TypeMirror sup = typeElement.getSuperclass();
        if (!sup.getKind().equals(TypeKind.NONE))
            return (TypeElement) ((DeclaredType) sup).asElement();
        else
            return null;
    }
    return env.getElementUtils().getTypeElement(Object.class.getName());
}
 
Example 14
Source File: AbstractTypedAnalyzer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected void collectAncestors(TypeElement type , Set<TypeElement> ancestors, 
        CompilationInfo compInfo )
{
    TypeMirror superclass = type.getSuperclass();
    addAncestor( superclass, ancestors, compInfo);
    List<? extends TypeMirror> interfaces = type.getInterfaces();
    for (TypeMirror interfaze : interfaces) {
        addAncestor(interfaze, ancestors, compInfo);
    }
}
 
Example 15
Source File: RetroWeiboProcessor.java    From SimpleWeibo with Apache License 2.0 5 votes vote down vote up
private boolean ancestorIsRetroWeibo(TypeElement type) {
  while (true) {
    TypeMirror parentMirror = type.getSuperclass();
    if (parentMirror.getKind() == TypeKind.NONE) {
      return false;
    }
    Types typeUtils = processingEnv.getTypeUtils();
    TypeElement parentElement = (TypeElement) typeUtils.asElement(parentMirror);
    if (parentElement.getAnnotation(RetroWeibo.class) != null) {
      return true;
    }
    type = parentElement;
  }
}
 
Example 16
Source File: AdapterInfo.java    From AnnotatedAdapter with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if this AnnotatedAdapter has another AnnotatedAdapter as super class. Therfore the
 * binder interface must extends from this one.
 */
public AdapterInfo getAnnotatedAdapterSuperClass(Map<String, AdapterInfo> adaptersMap) {

  if (searchedForSuperAnnotatedAdapterClass) {
    return superAnnotatedAdapterClass;
  }

  searchedForSuperAnnotatedAdapterClass = true;

  // Search from bottom up along inheritance three for the fist Annotated adapter class we find
  TypeElement currentClass = adapterClass;

  while (currentClass != null) {
    TypeMirror currentMirror = currentClass.getSuperclass();

    if (currentMirror instanceof NoType || currentMirror.getKind() == TypeKind.NONE) {
      // java.lang.Object has been found, there is no other super class
      return null;
    }

    AdapterInfo superAdapter = adaptersMap.get(currentMirror.toString());
    if (superAdapter != null) {
      // "Cache" the found super class for performance reasons
      superAnnotatedAdapterClass = superAdapter;
      return superAnnotatedAdapterClass;
    }

    // Continue with the super class
    currentClass = elementUtils.getTypeElement(currentMirror.toString());
  }

  return null;
}
 
Example 17
Source File: JsonAnnotationProcessor.java    From ig-json-parser with MIT License 4 votes vote down vote up
/**
 * This processes a single class that is annotated with {@link JsonType}. It verifies that the
 * class is public and creates an {@link ProcessorClassData} for it.
 */
private void processClassAnnotation(Element element) {
  boolean abstractClass = false;
  TypeElement typeElement = (TypeElement) element;

  // The annotation should be validated for an interface, but no code should be generated.
  JsonType annotation = element.getAnnotation(JsonType.class);
  if (element.getKind() == INTERFACE) {
    return;
  }

  boolean isKotlin = false;
  try {
    Class<? extends Annotation> metaDataClass =
        Class.forName("kotlin.Metadata").asSubclass(Annotation.class);
    isKotlin = element.getAnnotation(metaDataClass) != null;
  } catch (ClassNotFoundException e) {
    // not kotlin
  }

  // Verify containing class visibility is not private.
  if (element.getModifiers().contains(PRIVATE)) {
    error(
        element,
        "@%s %s may not be applied to private classes. (%s.%s)",
        JsonType.class.getSimpleName(),
        typeElement.getQualifiedName(),
        element.getSimpleName());
    return;
  }
  if (element.getModifiers().contains(ABSTRACT)) {
    abstractClass = true;
  }

  JsonParserClassData injector = mState.mClassElementToInjectorMap.get(typeElement);
  if (injector == null) {

    String parentGeneratedClassName = null;

    if (!mOmitSomeMethodBodies) {
      // Superclass info is only needed if we're generating method bodies.
      TypeMirror superclass = typeElement.getSuperclass();
      // walk up the superclass hierarchy until we find another class we know about.
      while (superclass.getKind() != TypeKind.NONE) {
        TypeElement superclassElement = (TypeElement) mTypes.asElement(superclass);

        if (superclassElement.getAnnotation(JsonType.class) != null) {
          String superclassPackageName = mTypeUtils.getPackageName(mElements, superclassElement);
          parentGeneratedClassName =
              superclassPackageName
                  + "."
                  + mTypeUtils.getPrefixForGeneratedClass(
                      superclassElement, superclassPackageName)
                  + JsonAnnotationProcessorConstants.HELPER_CLASS_SUFFIX;

          break;
        }

        superclass = superclassElement.getSuperclass();
      }
    }

    boolean generateSerializer =
        annotation.generateSerializer() == JsonType.TriState.DEFAULT
            ? mGenerateSerializers
            : annotation.generateSerializer() == JsonType.TriState.YES;

    String packageName = mTypeUtils.getPackageName(mElements, typeElement);
    injector =
        new JsonParserClassData(
            packageName,
            typeElement.getQualifiedName().toString(),
            mTypeUtils.getClassName(typeElement, packageName),
            mTypeUtils.getPrefixForGeneratedClass(typeElement, packageName)
                + JsonAnnotationProcessorConstants.HELPER_CLASS_SUFFIX,
            new ProcessorClassData.AnnotationRecordFactory<String, TypeData>() {

              @Override
              public TypeData createAnnotationRecord(String key) {
                return new TypeData();
              }
            },
            abstractClass,
            generateSerializer,
            mOmitSomeMethodBodies,
            parentGeneratedClassName,
            annotation,
            isKotlin);
    mState.mClassElementToInjectorMap.put(typeElement, injector);
  }
}
 
Example 18
Source File: MountSpecModelFactory.java    From litho with Apache License 2.0 4 votes vote down vote up
private static TypeName getMountType(
    Elements elements, TypeElement element, EnumSet<RunMode> runMode) {
  TypeElement viewType = elements.getTypeElement(ClassNames.VIEW_NAME);
  TypeElement drawableType = elements.getTypeElement(ClassNames.DRAWABLE_NAME);

  for (Element enclosedElement : element.getEnclosedElements()) {
    if (enclosedElement.getKind() != ElementKind.METHOD) {
      continue;
    }

    OnCreateMountContent annotation = enclosedElement.getAnnotation(OnCreateMountContent.class);
    if (annotation != null) {
      if (annotation.mountingType() == MountingType.VIEW) {
        return ClassNames.COMPONENT_LIFECYCLE_MOUNT_TYPE_VIEW;
      }
      if (annotation.mountingType() == MountingType.DRAWABLE) {
        return ClassNames.COMPONENT_LIFECYCLE_MOUNT_TYPE_DRAWABLE;
      }

      TypeMirror initialReturnType = ((ExecutableElement) enclosedElement).getReturnType();
      if (runMode.contains(RunMode.ABI)) {
        // We can't access the supertypes of the return type, so let's guess, and we'll verify
        // that our guess was correct when we do a full build later.
        if (initialReturnType.toString().contains("Drawable")) {
          return ClassNames.COMPONENT_LIFECYCLE_MOUNT_TYPE_DRAWABLE;
        } else {
          return ClassNames.COMPONENT_LIFECYCLE_MOUNT_TYPE_VIEW;
        }
      }

      TypeMirror returnType = initialReturnType;
      while (returnType.getKind() != TypeKind.NONE && returnType.getKind() != TypeKind.VOID) {
        final TypeElement returnElement = (TypeElement) ((DeclaredType) returnType).asElement();

        if (returnElement.equals(viewType)) {
          if (initialReturnType.toString().contains("Drawable")) {
            throw new ComponentsProcessingException(
                "Mount type cannot be correctly inferred from the name of "
                    + element
                    + ".  Please specify `@OnCreateMountContent(mountingType = MountingType.VIEW)`.");
          }

          return ClassNames.COMPONENT_LIFECYCLE_MOUNT_TYPE_VIEW;
        } else if (returnElement.equals(drawableType)) {
          if (!initialReturnType.toString().contains("Drawable")) {
            throw new ComponentsProcessingException(
                "Mount type cannot be correctly inferred from the name of "
                    + element
                    + ".  Please specify `@OnCreateMountContent(mountingType = MountingType.DRAWABLE)`.");
          }
          return ClassNames.COMPONENT_LIFECYCLE_MOUNT_TYPE_DRAWABLE;
        }

        try {
          returnType = returnElement.getSuperclass();
        } catch (RuntimeException e) {
          throw new ComponentsProcessingException(
              "Failed to get mount type for "
                  + element
                  + ".  Try specifying `@OnCreateMountContent(mountingType = MountingType.VIEW)` (or DRAWABLE).");
        }
      }
    }
  }

  return ClassNames.COMPONENT_LIFECYCLE_MOUNT_TYPE_NONE;
}
 
Example 19
Source File: ClassVisitorDriverFromElement.java    From buck with Apache License 2.0 4 votes vote down vote up
@Override
public Void visitType(TypeElement e, ClassVisitor visitor) {
  if (classVisitorStarted) {
    // We'll get inner class references later
    return null;
  }

  TypeMirror superclass = e.getSuperclass();
  if (superclass.getKind() == TypeKind.NONE) {
    superclass = Objects.requireNonNull(elements.getTypeElement("java.lang.Object")).asType();
  }

  int classFileVersion = SourceVersionUtils.sourceVersionToClassFileVersion(targetVersion);
  visitor.visit(
      classFileVersion,
      accessFlagsUtils.getAccessFlagsForClassNode(e),
      descriptorFactory.getInternalName(e),
      signatureFactory.getSignature(e),
      descriptorFactory.getInternalName(superclass),
      e.getInterfaces().stream()
          .map(descriptorFactory::getInternalName)
          .toArray(size -> new String[size]));
  classVisitorStarted = true;

  // Handle nests in Java 11+. See JEP 181 (https://openjdk.java.net/jeps/181) for details.
  if (classFileVersion >= Opcodes.V11) {
    if (e.getNestingKind().isNested()) {
      visitNestHost(e, visitor);
    } else {
      visitNestMembers(e, visitor);
    }
  }

  visitAnnotations(e, visitor::visitAnnotation);

  super.visitType(e, visitor);

  InnerClassesTable innerClassesTable =
      new InnerClassesTable(descriptorFactory, accessFlagsUtils, e);
  if (e.getKind().isClass() || classFileVersion >= Opcodes.V1_8) {
    try {
      generateBridges(e, visitor, innerClassesTable);
    } catch (UnsupportedOperationException | CannotInferException ex) { // NOPMD
      // Can't generate bridges in source-only mode
    }
  }

  innerClassesTable.reportInnerClassReferences(visitor);

  return null;
}
 
Example 20
Source File: InternalDomainMetaFactory.java    From doma with Apache License 2.0 4 votes vote down vote up
@Override
public void validateAccessorMethod(TypeElement classElement, InternalDomainMeta domainMeta) {
  TypeElement typeElement = classElement;
  TypeMirror typeMirror = classElement.asType();
  for (; typeElement != null && typeMirror.getKind() != TypeKind.NONE; ) {
    for (ExecutableElement method :
        ElementFilter.methodsIn(typeElement.getEnclosedElements())) {
      if (!method.getSimpleName().contentEquals(domainMeta.getAccessorMethod())) {
        continue;
      }
      if (method.getModifiers().contains(Modifier.PRIVATE)) {
        continue;
      }
      if (!method.getParameters().isEmpty()) {
        continue;
      }
      TypeMirror returnType = method.getReturnType();
      if (ctx.getMoreTypes()
          .isAssignableWithErasure(
              ctx.getMoreTypes().erasure(returnType), domainMeta.getValueType())) {
        return;
      }
      TypeVariable typeVariable = ctx.getMoreTypes().toTypeVariable(returnType);
      if (typeVariable != null) {
        TypeMirror inferredReturnType = inferType(typeVariable, typeElement, typeMirror);
        if (inferredReturnType != null) {
          if (ctx.getMoreTypes()
              .isAssignableWithErasure(inferredReturnType, domainMeta.getValueType())) {
            return;
          }
        }
      }
    }
    typeMirror = typeElement.getSuperclass();
    typeElement = ctx.getMoreTypes().toTypeElement(typeMirror);
  }
  throw new AptException(
      Message.DOMA4104,
      classElement,
      new Object[] {domainMeta.getAccessorMethod(), domainMeta.getValueType()});
}