Java Code Examples for javax.lang.model.type.DeclaredType#asElement()

The following examples show how to use javax.lang.model.type.DeclaredType#asElement() . 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: InterfaceValidator.java    From buck with Apache License 2.0 6 votes vote down vote up
private void ensureAbsentOrComplete(TypeMirror typeMirror, TreePath path) {
  if (typeMirror.getKind() != TypeKind.DECLARED) {
    return;
  }

  DeclaredType declaredType = (DeclaredType) typeMirror;
  TypeElement typeElement = (TypeElement) declaredType.asElement();
  CompletedType completedType = Objects.requireNonNull(completer.complete(typeElement, true));

  switch (completedType.kind) {
    case COMPLETED_TYPE:
    case PARTIALLY_COMPLETED_TYPE:
    case ERROR_TYPE:
      // These are all fine
      break;
    case CRASH:
      reportMissingDeps(completedType, path);
      break;
  }
}
 
Example 2
Source File: TypeUtilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public StringBuilder visitDeclared(DeclaredType t, Boolean p) {
    Element e = t.asElement();
    if (e instanceof TypeElement) {
        TypeElement te = (TypeElement)e;
        DEFAULT_VALUE.append((p ? te.getQualifiedName() : te.getSimpleName()).toString());
        Iterator<? extends TypeMirror> it = t.getTypeArguments().iterator();
        if (it.hasNext()) {
            DEFAULT_VALUE.append("<"); //NOI18N
            while(it.hasNext()) {
                visit(it.next(), p);
                if (it.hasNext())
                    DEFAULT_VALUE.append(", "); //NOI18N
            }
            DEFAULT_VALUE.append(">"); //NOI18N
        }
        return DEFAULT_VALUE;
    } else {
        return DEFAULT_VALUE.append(UNKNOWN); //NOI18N
    }
}
 
Example 3
Source File: MoreTypes.java    From auto with Apache License 2.0 6 votes vote down vote up
@Override
public Integer visitDeclared(DeclaredType t, Set<Element> visiting) {
  Element element = t.asElement();
  if (visiting.contains(element)) {
    return 0;
  }
  Set<Element> newVisiting = new HashSet<Element>(visiting);
  newVisiting.add(element);
  int result = hashKind(HASH_SEED, t);
  result *= HASH_MULTIPLIER;
  result += t.asElement().hashCode();
  result *= HASH_MULTIPLIER;
  result += t.getEnclosingType().accept(this, newVisiting);
  result *= HASH_MULTIPLIER;
  result += hashList(t.getTypeArguments(), newVisiting);
  return result;
}
 
Example 4
Source File: InferredTypeElementTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testAsType() throws IOException {
  compile(Joiner.on('\n').join("public class Foo extends com.example.buck.Bar.Baz {", "}"));

  DeclaredType superclass = (DeclaredType) elements.getTypeElement("Foo").getSuperclass();
  TypeElement element = (TypeElement) superclass.asElement();
  TypeMirror type = element.asType();

  assertEquals(TypeKind.DECLARED, type.getKind());
  DeclaredType fooDeclaredType = (DeclaredType) type;
  assertSame(element, fooDeclaredType.asElement());
}
 
Example 5
Source File: AutoMatterProcessor.java    From auto-matter with Apache License 2.0 5 votes vote down vote up
private String packageName(final DeclaredType declaredType) {
  Element type = declaredType.asElement();
  while (type.getKind() != ElementKind.PACKAGE) {
    type = type.getEnclosingElement();
  }
  return type.toString();
}
 
Example 6
Source File: CompletionSimulator.java    From buck with Apache License 2.0 5 votes vote down vote up
@Nullable
private CompletedType complete(TypeMirror type, boolean transitive) {
  if (type.getKind() != TypeKind.DECLARED) {
    return null;
  }

  DeclaredType declaredType = (DeclaredType) type;
  TypeElement element = (TypeElement) declaredType.asElement();
  return complete(element, transitive);
}
 
Example 7
Source File: DataBeanModel.java    From PowerfulRecyclerViewAdapter with Apache License 2.0 5 votes vote down vote up
@Override
public BeanInfo visitType(TypeElement element, Void aVoid) {
    //check element type
    if (!VALIDATED_CLASS_NAME.equals(getQualifiedName(element)))
        checkElementType(element, VALIDATED_CLASS_NAME);
    TypeMirror typeMirror = null;
    BeanInfo beanInfo = new BeanInfo();
    //get annotated Element info.
    String annotatedElementPackage = getPackageName(element);
    beanInfo.holderName = getSimpleName(element);
    beanInfo.holderPackage = annotatedElementPackage;
    //get annotation info
    try {
        DataBean dataBean = element.getAnnotation(DataBean.class);
        beanInfo.dataBeanName = dataBean.beanName();
        beanInfo.dataBeanPackage = annotatedElementPackage + ".databean";
        beanInfo.layoutId = dataBean.layout();
        //Get type of Data,may throw exception
        dataBean.data();
    } catch (MirroredTypeException mte) {
        typeMirror = mte.getTypeMirror();
    }
    if (typeMirror != null) {
        if (typeMirror.getKind() == TypeKind.DECLARED) {
            DeclaredType declaredType = (DeclaredType) typeMirror;
            TypeElement dataBeanElement = (TypeElement) declaredType.asElement();
            beanInfo.dataPackage = getPackageName(dataBeanElement);
            beanInfo.dataName = getSimpleName(dataBeanElement);
        }
    }
    //log
    logger.log(Diagnostic.Kind.NOTE,
            beanInfo.toString());
    return beanInfo;
}
 
Example 8
Source File: JpaControllerUtil.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public String getCodeToPopulatePkField(TypeElement type, ExecutableElement pkAccessorMethod) {
    EmbeddedPkSupportInfo info = getInfo(type);
    String code = info.getCodeToPopulatePkField(pkAccessorMethod);
    if (code != null) {
        return code;
    }
    
    code = "";
    ExecutableElement relationshipMethod = info.getRelationshipMethod(pkAccessorMethod);
    String referencedColumnName = info.getReferencedColumnName(pkAccessorMethod);
    if (relationshipMethod == null || referencedColumnName == null) {
        info.putCodeToPopulatePkField(pkAccessorMethod, code);
        return code;
    }
    
    TypeMirror relationshipTypeMirror = relationshipMethod.getReturnType();
    if (TypeKind.DECLARED != relationshipTypeMirror.getKind()) {
        info.putCodeToPopulatePkField(pkAccessorMethod, code);
        return code;
    }
    DeclaredType declaredType = (DeclaredType) relationshipTypeMirror;
    TypeElement relationshipType = (TypeElement) declaredType.asElement();
    
    EmbeddedPkSupportInfo relatedInfo = getInfo(relationshipType);
    String accessorString = relatedInfo.getAccessorString(referencedColumnName);
    if (accessorString == null) {
        info.putCodeToPopulatePkField(pkAccessorMethod, code);
        return code;
    }
    
    code = relationshipMethod.getSimpleName().toString() + "()." + accessorString;
    info.putCodeToPopulatePkField(pkAccessorMethod, code);
    return code;
}
 
Example 9
Source File: Util.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void addXmlRootAnnotation(WorkingCopy working, TreeMaker make){
    if ( working.getElements().getTypeElement(
            XMLROOT_ANNOTATION) == null)
    {
        return;
    }
    
    TypeElement entityElement = 
        working.getTopLevelElements().get(0);
    List<? extends AnnotationMirror> annotationMirrors = 
        working.getElements().getAllAnnotationMirrors(
                entityElement);
    boolean hasXmlRootAnnotation = false;
    for (AnnotationMirror annotationMirror : annotationMirrors)
    {
        DeclaredType type = annotationMirror.getAnnotationType();
        Element annotationElement = type.asElement();
        if ( annotationElement instanceof TypeElement ){
            Name annotationName = ((TypeElement)annotationElement).
                getQualifiedName();
            if ( annotationName.contentEquals(XMLROOT_ANNOTATION))
            {
                hasXmlRootAnnotation = true;
            }
        }
    }
    if ( !hasXmlRootAnnotation ){
        ClassTree classTree = working.getTrees().getTree(
                entityElement);
        GenerationUtils genUtils = GenerationUtils.
            newInstance(working);
        ModifiersTree modifiersTree = make.addModifiersAnnotation(
                classTree.getModifiers(),
                genUtils.createAnnotation(XMLROOT_ANNOTATION));

        working.rewrite( classTree.getModifiers(), 
                modifiersTree);
    }
}
 
Example 10
Source File: AbstractCommandSpecProcessor.java    From picocli with Apache License 2.0 5 votes vote down vote up
/**
 * Obtains the super type element for a given type element.
 *
 * @param element The type element
 * @return The super type element or null if none exists
 */
private static TypeElement superClassFor(TypeElement element) {
    TypeMirror superclass = element.getSuperclass();
    if (superclass.getKind() == TypeKind.NONE) {
        return null;
    }
    logger.finest(format("Superclass of %s is %s (of kind %s)", element, superclass, superclass.getKind()));
    DeclaredType kind = (DeclaredType) superclass;
    return (TypeElement) kind.asElement();
}
 
Example 11
Source File: ControllerGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public TypeMirror visitTypeVariable(TypeVariable t, CompilationInfo p) {
    TypeMirror lb = t.getLowerBound() == null ? null : visit(t.getLowerBound(), p);
    TypeMirror ub = t.getUpperBound() == null ? null : visit(t.getUpperBound(), p);
    if (ub.getKind() == TypeKind.DECLARED) {
        DeclaredType dt = (DeclaredType)ub;
        TypeElement tel = (TypeElement)dt.asElement();
        if (tel.getQualifiedName().contentEquals("java.lang.Object")) { // NOI18N
            ub = null;
        } else if (tel.getSimpleName().length() == 0) {
            ub = null;
        }
    }
    return p.getTypes().getWildcardType(ub, lb);
}
 
Example 12
Source File: T6421111.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
void test(TypeElement element, boolean fbound) {
    TypeParameterElement tpe = element.getTypeParameters().iterator().next();
    tpe.getBounds().getClass();
    if (fbound) {
        DeclaredType type = (DeclaredType)tpe.getBounds().get(0);
        if (type.asElement() != element)
            throw error("%s != %s", type.asElement(), element);
        TypeVariable tv = (TypeVariable)type.getTypeArguments().get(0);
        if (tv.asElement() != tpe)
            throw error("%s != %s", tv.asElement(), tpe);
    }
}
 
Example 13
Source File: AnnotationHelper.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * @return the annotation type name or null if <code>typeMirror</code>
 *         was not an annotation type.
 */
public String getAnnotationTypeName(DeclaredType typeMirror) {
    if (!TypeKind.DECLARED.equals(typeMirror.getKind())) {
        return null;
    }
    Element element = typeMirror.asElement();
    if (!ElementKind.ANNOTATION_TYPE.equals(element.getKind())) {
        return null;
    }
    return ((TypeElement)element).getQualifiedName().toString();
}
 
Example 14
Source File: JpaControllerUtil.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static List<String> getExceptionsThrown(WorkingCopy workingCopy, String fqClass, String methodName, List<String> formalParamFqTypes) {
    if (formalParamFqTypes == null) {
        formalParamFqTypes = Collections.<String>emptyList();
    }
    ExecutableElement desiredMethodElement = null;
    TypeElement suppliedTypeElement = workingCopy.getElements().getTypeElement(fqClass);
    TypeElement typeElement = suppliedTypeElement;
    whileloop:
    while (typeElement != null) {
        for (ExecutableElement methodElement : ElementFilter.methodsIn(typeElement.getEnclosedElements())) {
            if (methodElement.getSimpleName().contentEquals(methodName)) {
                List<? extends VariableElement> formalParamElements = methodElement.getParameters();
                //for now, just check sizes
                if (formalParamElements.size() == formalParamFqTypes.size()) {
                    desiredMethodElement = methodElement;
                    break whileloop;
                }
            }
        }
        typeElement = getSuperclassTypeElement(typeElement);
    }
    if (desiredMethodElement == null) {
        throw new IllegalArgumentException("Could not find " + methodName + " in " + fqClass);
    }
    List<String> result = new ArrayList<String>();
    List<? extends TypeMirror> thrownTypes = desiredMethodElement.getThrownTypes();
    for (TypeMirror thrownType : thrownTypes) {
        if (thrownType.getKind() == TypeKind.DECLARED) {
            DeclaredType thrownDeclaredType = (DeclaredType)thrownType;
            TypeElement thrownElement = (TypeElement)thrownDeclaredType.asElement();
            String thrownFqClass = thrownElement.getQualifiedName().toString();
            result.add(thrownFqClass);
        }
        else {
            result.add(null);
        }
    }
    return result;
}
 
Example 15
Source File: Environment.java    From sqlitemagic with Apache License 2.0 4 votes vote down vote up
@Override
public Element visitDeclared(DeclaredType t, Void p) {
  return t.asElement();
}
 
Example 16
Source File: ExpectedTypeResolver.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static void collectMethods(CompilationInfo info, 
        Scope accessor, ExecutableElement method, Collection<? extends TypeMirror> expectedReturnType, TypeMirror castableToType,
        DeclaredType dcc,
        List<TypeMirror> collected, Set<TypeMirror> seenTypes) {
    TypeElement c = (TypeElement)dcc.asElement();
    boolean tooAbstract = false;
    ExecutableElement found = null;

    if (!seenTypes.add(c.asType())) {
        return;
    }
    
    if (accessor == null || info.getTrees().isAccessible(accessor, c)) {
        for (ExecutableElement m : ElementFilter.methodsIn(c.getEnclosedElements())) {
            if (!m.getSimpleName().contentEquals(method.getSimpleName())) {
                continue;
            }
            if (accessor != null && !info.getTrees().isAccessible(accessor, m, dcc)) {
                continue;
            }
            if (m == method || info.getElements().overrides(method, m, c)) {
                if (expectedReturnType != null) {
                    if (assignableToSomeType(info, m.getReturnType(), expectedReturnType)) {
                        found = m;
                    } else {
                        tooAbstract = true;
                    }
                } else if (castableToType != null) {
                    if (info.getTypeUtilities().isCastable(m.getReturnType(), castableToType)) {
                        found = m;
                    }
                } else {
                    // no clue as for the return type -> accept the method.
                    found = m;
                }
                // in a hope the source is not broken, no other method may be overriden.
                break;
            }
        }
    }
    // if a overriden method is found, but its ret type was too abstract for the caller, then no super-overriden
    // method may be return type - compatible with the caller (can be only the same type, or a supertype thereof).
    if (!tooAbstract) {
        List<? extends TypeMirror> supertypes = info.getTypes().directSupertypes(dcc);
        for (TypeMirror supType : supertypes) {
            if (!(supType instanceof DeclaredType)) {
                continue;
            }
            collectMethods(info, accessor, method, expectedReturnType, 
                    castableToType, (DeclaredType)supType, collected, seenTypes);
        }
    }
    if (found != null) {
        addTypeAndReplaceMoreSpecific(info, collected, dcc);
    }
}
 
Example 17
Source File: FromEntityBase.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static void enumerateEntityFields(Map<String, Object> params, CompilationController controller, 
        TypeElement bean, String managedBeanProperty, boolean collectionComponent, boolean initValueGetters) {
    List<TemplateData> templateData = new ArrayList<TemplateData>();
    List<FieldDesc> fields = new ArrayList<FieldDesc>();
    String idFieldName = "";
    if (bean != null) {
        ExecutableElement[] methods = JpaControllerUtil.getEntityMethods(bean);
        JpaControllerUtil.EmbeddedPkSupport embeddedPkSupport = null;
        for (ExecutableElement method : methods) {
            // filter out @Transient methods
            if (JpaControllerUtil.findAnnotation(method, "javax.persistence.Transient") != null) { //NOI18N
                continue;
            }

            FieldDesc fd = new FieldDesc(controller, method, bean, initValueGetters);
            if (fd.isValid()) {
                int relationship = fd.getRelationship();
                if (EntityClass.isId(method, fd.isFieldAccess())) {
                    fd.setPrimaryKey();
                    idFieldName = fd.getPropertyName();
                    TypeMirror rType = method.getReturnType();
                    if (TypeKind.DECLARED == rType.getKind()) {
                        DeclaredType rTypeDeclared = (DeclaredType)rType;
                        TypeElement rTypeElement = (TypeElement) rTypeDeclared.asElement();
                        if (JpaControllerUtil.isEmbeddableClass(rTypeElement)) {
                            if (embeddedPkSupport == null) {
                                embeddedPkSupport = new JpaControllerUtil.EmbeddedPkSupport();
                            }
                            String propName = fd.getPropertyName();
                            for (ExecutableElement pkMethod : embeddedPkSupport.getPkAccessorMethods(bean)) {
                                if (!embeddedPkSupport.isRedundantWithRelationshipField(bean, pkMethod)) {
                                    String pkMethodName = pkMethod.getSimpleName().toString();
                                    fd = new FieldDesc(controller, pkMethod, bean);
                                    fd.setLabel(pkMethodName.substring(3));
                                    fd.setPropertyName(propName + "." + JpaControllerUtil.getPropNameFromMethod(pkMethodName));
                                    fields.add(fd);
                                }
                            }
                        } else {
                            fields.add(fd);
                        }
                        continue;
                    } else {
                        //primitive types
                        fields.add(fd);
                    }
                } else if (fd.getDateTimeFormat().length() > 0) {
                    fields.add(fd);
                } else if (relationship == JpaControllerUtil.REL_NONE || relationship == JpaControllerUtil.REL_TO_ONE) {
                    fields.add(fd);
                }
            }
        }
    }

    processFields(params, templateData, controller, bean, fields, managedBeanProperty, collectionComponent);

    params.put("entityDescriptors", templateData); // NOI18N
    params.put("item", ITEM_VAR); // NOI18N
    params.put("comment", Boolean.FALSE); // NOI18N
    params.put("entityIdField", idFieldName); //NOI18N
}
 
Example 18
Source File: Proto.java    From immutables with Apache License 2.0 4 votes vote down vote up
@Override
public TypeElement apply(DeclaredType input) {
  return (TypeElement) input.asElement();
}
 
Example 19
Source File: EventMethodExtractor.java    From litho with Apache License 2.0 4 votes vote down vote up
/** Get the delegate methods from the given {@link TypeElement}. */
public static ImmutableList<SpecMethodModel<EventMethod, EventDeclarationModel>>
    getOnEventMethods(
        Elements elements,
        TypeElement typeElement,
        List<Class<? extends Annotation>> permittedInterStageInputAnnotations,
        Messager messager,
        EnumSet<RunMode> runMode) {
  final List<SpecMethodModel<EventMethod, EventDeclarationModel>> delegateMethods =
      new ArrayList<>();

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

    final OnEvent onEventAnnotation = enclosedElement.getAnnotation(OnEvent.class);
    if (onEventAnnotation != null) {
      final ExecutableElement executableElement = (ExecutableElement) enclosedElement;

      final List<MethodParamModel> methodParams =
          getMethodParams(
              executableElement,
              messager,
              getPermittedMethodParamAnnotations(permittedInterStageInputAnnotations),
              permittedInterStageInputAnnotations,
              ImmutableList.<Class<? extends Annotation>>of());

      final DeclaredType eventClassDeclaredType =
          ProcessorUtils.getAnnotationParameter(
              elements, executableElement, OnEvent.class, "value", DeclaredType.class);
      final Element eventClass = eventClassDeclaredType.asElement();

      // In full mode, we get the return type from the Event class so that we can verify that it
      // matches the return type of the method. In ABI mode, we can't access the Event class so
      // we just use the method return type and leave validation for the full build.
      final TypeName returnType =
          runMode.contains(RunMode.ABI)
              ? TypeName.get(executableElement.getReturnType())
              : EventDeclarationsExtractor.getReturnType(elements, eventClass);
      final ImmutableList<FieldModel> fields =
          runMode.contains(RunMode.ABI)
              ? ImmutableList.of()
              : FieldsExtractor.extractFields(eventClass);

      final SpecMethodModel<EventMethod, EventDeclarationModel> eventMethod =
          SpecMethodModel.<EventMethod, EventDeclarationModel>builder()
              .annotations(ImmutableList.of())
              .modifiers(ImmutableList.copyOf(new ArrayList<>(executableElement.getModifiers())))
              .name(executableElement.getSimpleName())
              .returnTypeSpec(generateTypeSpec(executableElement.getReturnType()))
              .typeVariables(ImmutableList.copyOf(getTypeVariables(executableElement)))
              .methodParams(ImmutableList.copyOf(methodParams))
              .representedObject(executableElement)
              .typeModel(
                  new EventDeclarationModel(
                      ClassName.bestGuess(eventClass.toString()), returnType, fields, eventClass))
              .build();
      delegateMethods.add(eventMethod);
    }
  }

  return ImmutableList.copyOf(delegateMethods);
}
 
Example 20
Source File: Overrides.java    From auto with Apache License 2.0 4 votes vote down vote up
private TypeElement asTypeElement(TypeMirror typeMirror) {
  DeclaredType declaredType = MoreTypes.asDeclared(typeMirror);
  Element element = declaredType.asElement();
  return MoreElements.asType(element);
}