Java Code Examples for javax.lang.model.type.DeclaredType

The following examples show how to use javax.lang.model.type.DeclaredType. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
private void verifyTargetType() {

        TypeMirror expectedType = findExpectedType(pathToNewClassTree);
        if (!Utilities.isValidType(expectedType)) {
            foundErroneousTargetType = true;
            return;
        }

        TypeMirror erasedExpectedType = info.getTypes().erasure(expectedType);

        TreePath pathForClassIdentifier = new TreePath(pathToNewClassTree, newClassTree.getIdentifier());
        TypeMirror lambdaType = info.getTrees().getTypeMirror(pathForClassIdentifier);
        lambdaType = info.getTypes().erasure(lambdaType);

        foundAssignmentToSupertype = !info.getTypes().isSameType(erasedExpectedType, lambdaType);
        
        if (erasedExpectedType.getKind() == TypeKind.DECLARED) {
            TypeElement te = (TypeElement)((DeclaredType)erasedExpectedType).asElement();
            TypeMirror tt = (DeclaredType)te.asType();
            if (tt.getKind() == TypeKind.DECLARED && !((DeclaredType)tt).getTypeArguments().isEmpty()) {
                foundAssignmentToRawType =  info.getTypes().isSameType(erasedExpectedType, expectedType);
            }
        }
    }
 
Example 2
Source Project: pocketknife   Source File: BaseProcessor.java    License: Apache License 2.0 6 votes vote down vote up
protected void validateSerializer(Element element, Class<? extends Annotation> annotation, TypeMirror serializer, Class abstractSerializer) {
    if (serializer == null) {
        return;
    }
    Element absSerializerElement = elements.getTypeElement(abstractSerializer.getName());
    if (absSerializerElement == null) {
        throw new IllegalStateException(String.format("Unable to find %s type", abstractSerializer.getName()));
    }
    TypeMirror absSerializerMirror = absSerializerElement.asType();
    if (!types.isAssignable(serializer, types.erasure(absSerializerMirror))) {
        throw new IllegalStateException(String.format("@%s value must extend %s", annotation.getName(), abstractSerializer.getName()));
    }
    TypeMirror elementType = element.asType();
    for (TypeMirror superType : types.directSupertypes(serializer)) {
        if (types.isAssignable(superType, types.erasure(absSerializerMirror)) &&  superType instanceof DeclaredType) {
            if (types.isSameType(((DeclaredType) superType).getTypeArguments().get(0), elementType)) {
                return;
            } else {
                throw new IllegalStateException(String.format("Serializer T must be of type %s", elementType.toString()));
            }
        }
    }
    throw new IllegalStateException(String.format("%s must extend %s", serializer.toString(), absSerializerMirror.toString()));
}
 
Example 3
protected boolean classImplementsSei(TypeElement classElement, TypeElement interfaceElement) {
    for (TypeMirror interfaceType : classElement.getInterfaces()) {
        if (((DeclaredType) interfaceType).asElement().equals(interfaceElement))
            return true;
    }
    List<ExecutableElement> classMethods = getClassMethods(classElement);
    boolean implementsMethod;
    for (ExecutableElement interfaceMethod : ElementFilter.methodsIn(interfaceElement.getEnclosedElements())) {
        implementsMethod = false;
        for (ExecutableElement classMethod : classMethods) {
            if (sameMethod(interfaceMethod, classMethod)) {
                implementsMethod = true;
                classMethods.remove(classMethod);
                break;
            }
        }
        if (!implementsMethod) {
            builder.processError(WebserviceapMessages.WEBSERVICEAP_METHOD_NOT_IMPLEMENTED(interfaceElement.getSimpleName(), classElement.getSimpleName(), interfaceMethod), interfaceMethod);
            return false;
        }
    }
    return true;
}
 
Example 4
Source Project: netbeans   Source File: ElementJavadoc.java    License: Apache License 2.0 6 votes vote down vote up
private void appendAnnotation(StringBuilder sb, AnnotationMirror annotationDesc, boolean topLevel) {
    DeclaredType annotationType = annotationDesc.getAnnotationType();
    if (annotationType != null && (!topLevel || isDocumented(annotationType))) {
        appendType(sb, annotationType, false, false, true);
        Map<? extends ExecutableElement, ? extends AnnotationValue> values = annotationDesc.getElementValues();
        if (!values.isEmpty()) {
            sb.append('('); //NOI18N
            for (Iterator<? extends Map.Entry<? extends ExecutableElement, ? extends AnnotationValue>> it = values.entrySet().iterator(); it.hasNext();) {
                Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> value = it.next();
                createLink(sb, value.getKey(), value.getKey().getSimpleName());
                sb.append('='); //NOI18N
                appendAnnotationValue(sb, value.getValue());
                if (it.hasNext())
                    sb.append(","); //NOI18N
            }
            sb.append(')'); //NOI18N
        }
        if (topLevel)
            sb.append("<br>"); //NOI18N
    }
}
 
Example 5
Source Project: netbeans   Source File: SpringXMLConfigCompletionItem.java    License: 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 6
Source Project: domino-jackson   Source File: DeserializerGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private void generateSubTypesDeserializers(TypeMirror beanType, String packageName) {
	SubTypesInfo subTypesInfo= Type.getSubTypes(beanType);
    for (Map.Entry<String, TypeMirror> subtypeEntry: subTypesInfo.getSubTypes().entrySet()) {
    	// @JsonTypeInfo and @JsonSubTypes must be used only on non generic types
    	// This limitation is imposed by the the the java.land.model API, which does 
    	// not allow to retrieve interface(s) for given class (i.e. using getSupperClass()). 
    	// That limits the possibilities to inspect interface type parameters. Even
    	// beanType is TypeMirror for base interface (i.e. annotated with @JsonTypeInfo and @JsonSubTypes)
    	// with specified type arguments, we can not match them against the 
    	// type parameters of the subtype retrieved by @JsonSubTypes.
    	if (
    			!((DeclaredType)beanType).getTypeArguments().isEmpty()
    			|| !((DeclaredType)((DeclaredType)subtypeEntry.getValue()).asElement().asType()).getTypeArguments().isEmpty())
    		throw new RuntimeException("@JsonSubTypes and &JsonTypeInfo can be used only on non-generic Java types");

    	new DeserializerGenerator().generate(packageName, subtypeEntry.getValue());
    }
}
 
Example 7
Source Project: TencentKona-8   Source File: TypeModeler.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static TypeMirror getHolderValueType(TypeMirror type, TypeElement defHolder, ProcessingEnvironment env) {
    TypeElement typeElement = getDeclaration(type);
    if (typeElement == null)
        return null;

    if (isSubElement(typeElement, defHolder)) {
        if (type.getKind().equals(TypeKind.DECLARED)) {
            Collection<? extends TypeMirror> argTypes = ((DeclaredType) type).getTypeArguments();
            if (argTypes.size() == 1) {
                return argTypes.iterator().next();
            } else if (argTypes.isEmpty()) {
                VariableElement member = getValueMember(typeElement);
                if (member != null) {
                    return member.asType();
                }
            }
        }
    }
    return null;
}
 
Example 8
Source Project: netbeans   Source File: AnnotationObjectProvider.java    License: Apache License 2.0 6 votes vote down vote up
static void findQualifiers(Element element , 
        AnnotationModelHelper helper , boolean event , 
        AnnotationHandleStrategy strategy )
{
    List<? extends AnnotationMirror> allAnnotationMirrors = 
        helper.getCompilationController().getElements().
        getAllAnnotationMirrors( element );
    for (AnnotationMirror annotationMirror : allAnnotationMirrors) {
        DeclaredType annotationType = annotationMirror
                .getAnnotationType();
        if ( annotationType == null || annotationType.getKind() == TypeKind.ERROR){
            continue;
        }
        TypeElement annotationElement = (TypeElement) annotationType
                .asElement();
        if (annotationElement!= null && isQualifier(annotationElement, 
                helper , event )) 
        {
            strategy.handleAnnotation(annotationMirror , annotationElement );
        }
    }
}
 
Example 9
Source Project: Akatsuki   Source File: PrimitiveTypeAnalyzer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public DefaultAnalysis createAnalysis(InvocationContext<TypeMirror> context)
		throws UnknownTypeException {
	// boxed primitives have different names (at least for int)
	CharSequence typeName;
	final TypeMirror refinedMirror = context.field.refinedMirror();
	if (refinedMirror instanceof DeclaredType) {
		// we are boxed
		typeName = this.type == Type.UNBOXED
				? toCapitalCase(types().unboxedType(refinedMirror).getKind().name())
				: ((DeclaredType) refinedMirror).asElement().getSimpleName();
	} else {
		// we are unboxed
		typeName = this.type == Type.BOXED
				? types().boxedClass((PrimitiveType) refinedMirror).getSimpleName()
				: toCapitalCase(refinedMirror.getKind().name());
	}
	String methodName = (suffix != null) ? (typeName.toString() + suffix) : typeName.toString();
	return DefaultAnalysis.of(this, methodName, context);
}
 
Example 10
Source Project: netbeans   Source File: EventsModel.java    License: Apache License 2.0 6 votes vote down vote up
private void update( List<VariableElement> vars , 
        CompilationController controller) 
{
    DefaultMutableTreeNode root = new DefaultMutableTreeNode();
    
    for (VariableElement var : vars) {
        FileObject fileObject = SourceUtils.getFile(ElementHandle
                .create(var), controller.getClasspathInfo());
        InjectableTreeNode<Element> node = 
            new InjectableTreeNode<Element>(fileObject, var,  
                    (DeclaredType)controller.getElementUtilities().
                    enclosingTypeElement(var).asType(), false,controller);
        root.add( node );
    }
    setRoot(root);
}
 
Example 11
Source Project: hottub   Source File: TypeModeler.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static TypeMirror getHolderValueType(TypeMirror type, TypeElement defHolder, ProcessingEnvironment env) {
    TypeElement typeElement = getDeclaration(type);
    if (typeElement == null)
        return null;

    if (isSubElement(typeElement, defHolder)) {
        if (type.getKind().equals(TypeKind.DECLARED)) {
            Collection<? extends TypeMirror> argTypes = ((DeclaredType) type).getTypeArguments();
            if (argTypes.size() == 1) {
                return argTypes.iterator().next();
            } else if (argTypes.isEmpty()) {
                VariableElement member = getValueMember(typeElement);
                if (member != null) {
                    return member.asType();
                }
            }
        }
    }
    return null;
}
 
Example 12
Source Project: immutables   Source File: CriteriaModel.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Criteria templates are always generated as top-level class (separate file).
 * Construct criteria name from {@linkplain TypeMirror}
 *
 * @return fully qualified criteria (template) class name
 */
private static String topLevelCriteriaClassName(TypeMirror type) {
  DeclaredType declaredType = MoreTypes.asDeclared(type);
  Element element = declaredType.asElement();
  do {
    element = element.getEnclosingElement();
  } while (element.getKind() != ElementKind.PACKAGE);

  String packagePrefix = "";
  if (!element.getSimpleName().contentEquals("")) {
    packagePrefix = MoreElements.asPackage(element).getQualifiedName() + ".";
  }

  // package name + type name + "CriteriaTemplate"
  return packagePrefix + declaredType.asElement().getSimpleName().toString() + "CriteriaTemplate";
}
 
Example 13
Source Project: netbeans   Source File: SpringXMLConfigCompletionItem.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public StringBuilder visitWildcard(WildcardType t, Boolean p) {
    DEFAULT_VALUE.append("?"); //NOI18N
    TypeMirror bound = t.getSuperBound();
    if (bound == null) {
        bound = t.getExtendsBound();
        if (bound != null) {
            DEFAULT_VALUE.append(" extends "); //NOI18N
            if (bound.getKind() == TypeKind.WILDCARD)
                bound = ((WildcardType)bound).getSuperBound();
            visit(bound, p);
        } else {
            bound = SourceUtils.getBound(t);
            if (bound != null && (bound.getKind() != TypeKind.DECLARED || !((TypeElement)((DeclaredType)bound).asElement()).getQualifiedName().contentEquals("java.lang.Object"))) { //NOI18N
                DEFAULT_VALUE.append(" extends "); //NOI18N
                visit(bound, p);
            }
        }
    } else {
        DEFAULT_VALUE.append(" super "); //NOI18N
        visit(bound, p);
    }
    return DEFAULT_VALUE;
}
 
Example 14
private static KindOfType detectKind(CompilationInfo info, TypeMirror tm) {
    if (tm.getKind().isPrimitive()) {
        return KindOfType.valueOf(tm.getKind().name());
    }

    if (tm.getKind() == TypeKind.ARRAY) {
        return ((ArrayType) tm).getComponentType().getKind().isPrimitive() ? KindOfType.ARRAY_PRIMITIVE : KindOfType.ARRAY;
    }

    if (tm.getKind() == TypeKind.DECLARED) {
        Types t = info.getTypes();
        TypeElement en = info.getElements().getTypeElement("java.lang.Enum");

        if (en != null) {
            if (t.isSubtype(tm, t.erasure(en.asType()))) {
                return KindOfType.ENUM;
            }
        }

        if (((DeclaredType) tm).asElement().getKind().isClass() && ((TypeElement) ((DeclaredType) tm).asElement()).getQualifiedName().contentEquals("java.lang.String")) {
            return KindOfType.STRING;
        }
    }

    return KindOfType.OTHER;
}
 
Example 15
Source Project: lightcycle   Source File: LightCycleProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private LightCycleBinder findParent(Set<String> erasedTargetNames, TypeMirror type) {
    if (type.getKind() == TypeKind.NONE) {
        return LightCycleBinder.EMPTY;
    }

    final TypeElement typeElement = (TypeElement) ((DeclaredType) type).asElement();
    if (erasedTargetNames.contains(typeElement.toString())) {
        final String parentWithLightCycle = elementUtils.getBinaryName(typeElement).toString();
        return LightCycleBinder.forParent(binderName(parentWithLightCycle));
    }
    return findParent(erasedTargetNames, typeElement.getSuperclass());
}
 
Example 16
Source Project: netbeans   Source File: JavadocHelper.java    License: Apache License 2.0 5 votes vote down vote up
private static void appendType(FragmentBuilder fb, TypeMirror type, boolean varArg) {
    switch (type.getKind()) {
    case ARRAY:
        appendType(fb, ((ArrayType) type).getComponentType(), false);
        fb.append(varArg ? "..." : "[]"); // NOI18N
        break;
    case DECLARED:
        fb.append(((TypeElement) ((DeclaredType) type).asElement()).getQualifiedName());
        break;
    default:
        fb.append(type.toString());
    }
}
 
Example 17
Source Project: RetroFacebook   Source File: TypeSimplifier.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isJavaLangObject(TypeMirror type) {
  if (type.getKind() != TypeKind.DECLARED) {
    return false;
  }
  DeclaredType declaredType = (DeclaredType) type;
  TypeElement typeElement = (TypeElement) declaredType.asElement();
  return typeElement.getQualifiedName().contentEquals("java.lang.Object");
}
 
Example 18
Source Project: openjdk-jdk9   Source File: ApNavigator.java    License: GNU General Public License v2.0 5 votes vote down vote up
public TypeMirror erasure(TypeMirror t) {
    Types tu = env.getTypeUtils();
    t = tu.erasure(t);
    if (t.getKind().equals(TypeKind.DECLARED)) {
        DeclaredType dt = (DeclaredType)t;
        if (!dt.getTypeArguments().isEmpty())
            return tu.getDeclaredType((TypeElement) dt.asElement());
    }
    return t;
}
 
Example 19
Source Project: netbeans   Source File: WebBeansModelProviderImpl.java    License: Apache License 2.0 5 votes vote down vote up
private String doGetName( Element original , Element element ){
    List<? extends AnnotationMirror> annotations = getModel().getHelper().
        getCompilationController().getElements().getAllAnnotationMirrors( 
            element);
    for (AnnotationMirror annotationMirror : annotations) {
    DeclaredType type = annotationMirror.getAnnotationType();
    TypeElement annotationElement = (TypeElement)type.asElement();
        if ( NAMED_QUALIFIER_ANNOTATION.contentEquals( 
                annotationElement.getQualifiedName()))
        {
            return getNamedName( original , annotationMirror );
        }
    }
    return null;
}
 
Example 20
Source Project: FreeBuilder   Source File: FunctionalType.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the functional type accepted by {@code methodName} on {@code type}, assignable to
 * {@code prototype}, or {@code prototype} itself if no such method has been declared.
 *
 * <p>Used to allow the user to override the functional interface used on builder methods,
 * e.g. to force boxing, or to use Guava types.
 */
public static FunctionalType functionalTypeAcceptedByMethod(
    DeclaredType type,
    String methodName,
    FunctionalType prototype,
    Elements elements,
    Types types) {
  return functionalTypesAcceptedByMethod(type, methodName, elements, types)
      .stream()
      .filter(functionalType -> isAssignable(functionalType, prototype, types))
      .findAny()
      .orElse(prototype);
}
 
Example 21
Source Project: fastjgame   Source File: DefaultCodecGenerator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取参数的具体类型
 */
private DeclaredType getMapOrCollectionImp(VariableElement variableElement) {
    final DeclaredType declaredType = AutoUtils.getDeclaredType(variableElement.asType());
    if (!declaredType.asElement().getModifiers().contains(Modifier.ABSTRACT)) {
        // 声明类型是具体类型
        return declaredType;
    }

    if (processor.isEnumMap(declaredType) || processor.isEnumSet(declaredType)) {
        // 声明类型是EnumMap 或 EnumSet
        return declaredType;
    }

    return (DeclaredType) processor.getFieldImplAnnotationValue(variableElement);
}
 
Example 22
Source Project: Akatsuki   Source File: ProcessorUtils.java    License: Apache License 2.0 5 votes vote down vote up
private TypeMirror toUnboundDeclaredType(TypeMirror mirror) {
	if (mirror.getKind() != TypeKind.DECLARED)
		return mirror;
	final List<? extends TypeMirror> types = getGenericTypes(mirror);
	if (types.isEmpty())
		return mirror;
	TypeElement lhsElement = (TypeElement) ((DeclaredType) mirror).asElement();
	return this.types.getDeclaredType(lhsElement, synthesizeUnboundType(types.size()));
}
 
Example 23
Source Project: revapi   Source File: ExceptionsThrownChanged.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public TypeElement visitDeclared(DeclaredType t, Void ignored) {
    return t.asElement().accept(new SimpleElementVisitor7<TypeElement, Void>() {
        @Override
        public TypeElement visitType(TypeElement e, Void aVoid) {
            return e;
        }
    }, null);
}
 
Example 24
Source Project: butterknife   Source File: ButterKnifeProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private @Nullable TypeElement getSuperClass(TypeElement typeElement) {
  TypeMirror type = typeElement.getSuperclass();
  if (type.getKind() == TypeKind.NONE) {
    return null;
  }
  return (TypeElement) ((DeclaredType) type).asElement();
}
 
Example 25
Source Project: turbine   Source File: TurbineTypes.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public DeclaredType getDeclaredType(TypeElement typeElem, TypeMirror... typeArgs) {
  requireNonNull(typeElem);
  ImmutableList.Builder<Type> args = ImmutableList.builder();
  for (TypeMirror t : typeArgs) {
    args.add(asTurbineType(t));
  }
  TurbineTypeElement element = (TurbineTypeElement) typeElem;
  return (DeclaredType)
      factory.asTypeMirror(
          ClassTy.create(
              ImmutableList.of(
                  SimpleClassTy.create(element.sym(), args.build(), ImmutableList.of()))));
}
 
Example 26
Source Project: hottub   Source File: JavahTask.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public Void visitDeclared(DeclaredType t, Types types) {
    t.asElement().getKind(); // ensure class exists
    for (TypeMirror st: types.directSupertypes(t))
        visit(st, types);
    return null;
}
 
Example 27
Source Project: reflection-no-reflection   Source File: Processor.java    License: Apache License 2.0 5 votes vote down vote up
private String getTypeName(Element typeElement) {
    String injectedClassName = null;
    final TypeMirror fieldTypeMirror = typeElement.asType();
    if (fieldTypeMirror instanceof DeclaredType) {
        injectedClassName = ((TypeElement) ((DeclaredType) fieldTypeMirror).asElement()).getQualifiedName().toString();
    } else if (fieldTypeMirror instanceof PrimitiveType) {
        injectedClassName = fieldTypeMirror.toString();
    } else if (fieldTypeMirror instanceof ArrayType) {
        injectedClassName = ((ArrayType) fieldTypeMirror).getComponentType().toString() + "[]";
    }
    return injectedClassName;
}
 
Example 28
Source Project: revapi   Source File: MissingTypeAwareDelegatingTypes.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public DeclaredType getDeclaredType(DeclaredType containing, TypeElement typeElem, TypeMirror... typeArgs) {
    if (isMissing(containing)) {
        throw new IllegalArgumentException("Invalid containing type.");
    }
    if (typeElem instanceof MissingTypeElement) {
        throw new IllegalArgumentException("Invalid type element.");
    }
    for (TypeMirror t : typeArgs) {
        if (isMissing(t)) {
            throw new IllegalArgumentException("Invalid type arguments.");
        }
    }
    return IgnoreCompletionFailures.in(types::getDeclaredType, containing, typeElem, typeArgs);
}
 
Example 29
Source Project: netbeans   Source File: JSClientGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private TypeMirror getParameterType( TypeMirror type ){
    if ( type instanceof DeclaredType ){
        List<? extends TypeMirror> typeArguments = ((DeclaredType)type).getTypeArguments();
        if (typeArguments.isEmpty()) {
            return null;
        }
        return typeArguments.get(0);
    }
    return null;
}
 
Example 30
Source Project: jdk8u60   Source File: ApNavigator.java    License: GNU General Public License v2.0 5 votes vote down vote up
public boolean isParameterizedType(TypeMirror typeMirror) {
    if (typeMirror != null && typeMirror.getKind().equals(TypeKind.DECLARED)) {
        DeclaredType d = (DeclaredType) typeMirror;
        return !d.getTypeArguments().isEmpty();
    }
    return false;
}