Java Code Examples for javax.lang.model.type.TypeMirror#getKind()

The following examples show how to use javax.lang.model.type.TypeMirror#getKind() . 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: EntityMetaGenerator.java    From requery with Apache License 2.0 6 votes vote down vote up
private static Class propertyClassFor(TypeMirror typeMirror) {
    if (typeMirror.getKind().isPrimitive()) {
        switch (typeMirror.getKind()) {
            case BOOLEAN:
                return BooleanProperty.class;
            case BYTE:
                return ByteProperty.class;
            case SHORT:
                return ShortProperty.class;
            case INT:
                return IntProperty.class;
            case LONG:
                return LongProperty.class;
            case FLOAT:
                return FloatProperty.class;
            case DOUBLE:
                return DoubleProperty.class;
        }
    }
    return Property.class;
}
 
Example 2
Source File: Utils.java    From paperparcel with Apache License 2.0 6 votes vote down vote up
private static void getFieldsToParcelImpl(
    TypeElement element,
    OptionsDescriptor options,
    ImmutableList.Builder<VariableElement> fields,
    Set<Name> seenFieldNames) {
  for (VariableElement variable : fieldsIn(element.getEnclosedElements())) {
    if (!excludeViaModifiers(variable, options.excludeModifiers())
        && !usesAnyAnnotationsFrom(variable, options.excludeAnnotationNames())
        && !seenFieldNames.contains(variable.getSimpleName())
        && (!options.excludeNonExposedFields()
        || usesAnyAnnotationsFrom(variable, options.exposeAnnotationNames()))) {
      fields.add(variable);
      seenFieldNames.add(variable.getSimpleName());
    }
  }
  TypeMirror superType = element.getSuperclass();
  if (superType.getKind() != TypeKind.NONE) {
    TypeElement superElement = asType(asDeclared(superType).asElement());
    getFieldsToParcelImpl(superElement, options, fields, seenFieldNames);
  }
}
 
Example 3
Source File: DeptectiveTreeVisitor.java    From deptective with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the qualified Package Name of the given Tree object or null if the package could not be determined
 */
protected String getQualifiedPackageName(Tree tree) {
    TypeMirror typeMirror = trees.getTypeMirror(getCurrentPath());
    if (typeMirror == null) {
        return null;
    }

    if (typeMirror.getKind() != TypeKind.DECLARED && typeMirror.getKind() != TypeKind.TYPEVAR) {
        return null;
    }

    Element typeMirrorElement = types.asElement(typeMirror);
    if (typeMirrorElement == null) {
        throw new IllegalStateException("Could not get Element for type '" + typeMirror + "'");
    }
    PackageElement pakkage = elements.getPackageOf(typeMirrorElement);
    return pakkage.getQualifiedName().toString();
}
 
Example 4
Source File: ConverterTemplate.java    From dsl-json with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void buildArrayType(TypeMirror type, Map<String, Integer> typeVariableIndexes) throws IOException {
	if (type.getKind() == TypeKind.DECLARED) {
		DeclaredType declaredType = (DeclaredType) type;
		if (declaredType.getTypeArguments().isEmpty()) {
			code.append(type.toString());
		} else {
			String fullName = type.toString();
			int first = fullName.indexOf('<');
			code.append(fullName, 0, first);
		}
		code.append(".class");
	} else if (type.getKind() == TypeKind.ARRAY) {
		ArrayType arrayType = (ArrayType) type;
		code.append("com.dslplatform.json.runtime.Generics.makeArrayType(");
		buildArrayType(arrayType.getComponentType(), typeVariableIndexes);
		code.append(")");
	} else if (typeVariableIndexes.containsKey(type.toString())) {
		code.append("actualTypes[").append(Integer.toString(typeVariableIndexes.get(type.toString()))).append("]");
	} else {
		code.append(type.toString()).append(".class");
	}
}
 
Example 5
Source File: VarArgsCast.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public List<Fix> run(CompilationInfo info, String diagnosticKey, int offset, TreePath treePath, Data<Void> data) {
    TreePath call = treePath;//.getParentPath();
    
    if (call.getLeaf().getKind() != Kind.METHOD_INVOCATION) {
        call = call.getParentPath();
        if (call.getLeaf().getKind() != Kind.METHOD_INVOCATION) {
            return null;
        }
    }
    
    MethodInvocationTree mit = (MethodInvocationTree) call.getLeaf();
    TypeMirror mType = info.getTrees().getTypeMirror(new TreePath(call, mit.getMethodSelect()));
    
    if (mType == null || mType.getKind() != TypeKind.EXECUTABLE) {
        return null;
    }
    
    ExecutableType methodType = (ExecutableType) mType;
    
    if (methodType.getParameterTypes().isEmpty() || methodType.getParameterTypes().get(methodType.getParameterTypes().size() - 1).getKind() != TypeKind.ARRAY) {
        return null;
    }
    
    ArrayType targetArray = (ArrayType) methodType.getParameterTypes().get(methodType.getParameterTypes().size() - 1);
    TreePath target = new TreePath(call, mit.getArguments().get(mit.getArguments().size() - 1));
    
    return Arrays.asList(new FixImpl(info, target, targetArray.getComponentType()).toEditorFix(),
                         new FixImpl(info, target, targetArray).toEditorFix());
}
 
Example 6
Source File: ConstantNameHint.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean isImmutableType(CompilationInfo info, TypeMirror m, Preferences p) {
    if (m == null) {
        return false;
    }
    if (m.getKind().isPrimitive() || !isValidType(m)) {
        return true;
    }
    if (Utilities.isPrimitiveWrapperType(m)) {
        return true;
    }
    if (m.getKind() != TypeKind.DECLARED) {
        return false;
    }
    Element e = ((DeclaredType)m).asElement();
    if (e == null) {
        return false;
    }
    if (e.getKind() == ElementKind.ENUM) {
        return true;
    }
    if (e.getKind() != ElementKind.CLASS) {
        return false;
    }
    String qn = ((TypeElement)e).getQualifiedName().toString();
    
    if (IMMUTABLE_JDK_CLASSES.contains(qn)) {
        return true;
    }
    List<String> classes = getImmutableTypes(p);
    return classes.contains(qn);
}
 
Example 7
Source File: KratosProcessor.java    From Kratos with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void parseLBindText(Element element, Map<TypeElement, BindingClass> targetClassMap,
                            Set<String> erasedTargetNames) {
    TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();

    TypeMirror elementType = element.asType();
    if (elementType.getKind() == TypeKind.TYPEVAR) {
        TypeVariable typeVariable = (TypeVariable) elementType;
        elementType = typeVariable.getUpperBound();
    }
    // Assemble information on the field.
    String[] ids = element.getAnnotation(LBindText.class).value();
    BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement, true, false);
    for (String id : ids) {
        if (bindingClass != null) {
            KBindings bindings = bindingClass.getKBindings(id);
            if (bindings != null) {
                Iterator<FieldViewBinding> iterator = bindings.getFieldBindings().iterator();
                if (iterator.hasNext()) {
                    FieldViewBinding existingBinding = iterator.next();
                    error(element, "Attempt to use @%s for an already bound ID %s on '%s'. (%s.%s)",
                            LBindText.class.getSimpleName(), id, existingBinding.getName(),
                            enclosingElement.getQualifiedName(), element.getSimpleName());
                    return;
                }
            }
        } else {
            bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement, true, false);
        }
        String name = element.getSimpleName().toString();
        TypeName type = TypeName.get(elementType);
        boolean required = isRequiredBinding(element);

        FieldViewBinding binding = new FieldViewBinding(name, type, required);
        bindingClass.addField(String.valueOf(id), binding);
    }

    // Add the type-erased version to the valid binding targets set.
    erasedTargetNames.add(enclosingElement.toString());
}
 
Example 8
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Determines if assignment looses precision.
 * Works only for primitive types, false for references.
 * 
 * @param from the assigned value type
 * @param to the target type
 * @return true, if precision is lost
 */
public static boolean loosesPrecision(TypeMirror from, TypeMirror to) {
    if (!from.getKind().isPrimitive() || !to.getKind().isPrimitive()) {
        return false;
    }
    if (to.getKind() == TypeKind.CHAR) {
        return true;
    } else if (from.getKind() == TypeKind.CHAR) {
        return to.getKind() == TypeKind.BYTE || to.getKind() == TypeKind.SHORT;
    }
    return to.getKind().ordinal() < from.getKind().ordinal();
}
 
Example 9
Source File: InterceptorBindingMembersAnalyzer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected void checkMembers( TypeElement element, CdiAnalysisResult result , 
        String localizedWarning ) 
{
    List<ExecutableElement> methods = ElementFilter.methodsIn(
            element.getEnclosedElements());
    for (ExecutableElement executableElement : methods) {
        TypeMirror returnType = executableElement.getReturnType();
        boolean warning = false;
        if ( returnType.getKind() == TypeKind.ARRAY ){
            warning = true;
        }
        else if ( returnType.getKind() == TypeKind.DECLARED){
            Element returnElement = result.getInfo().getTypes().asElement( 
                    returnType );
            warning = returnElement.getKind() == ElementKind.ANNOTATION_TYPE;
        }
        if ( !warning ){
            continue;
        }
        if (AnnotationUtil.hasAnnotation(executableElement, 
                AnnotationUtil.NON_BINDING,  result.getInfo()) )
        {
            continue;
        }
        result.addNotification(Severity.WARNING, element, localizedWarning); 
    }
}
 
Example 10
Source File: MoreElements.java    From buck with Apache License 2.0 5 votes vote down vote up
@Nullable
public static TypeElement getSuperclass(TypeElement type) {
  TypeMirror superclassType = type.getSuperclass();
  switch (superclassType.getKind()) {
    case DECLARED:
    case ERROR:
      return (TypeElement) ((DeclaredType) superclassType).asElement();
    case NONE:
      return null;
      // $CASES-OMITTED$
    default:
      throw new IllegalArgumentException(superclassType.toString());
  }
}
 
Example 11
Source File: TmpPattern.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Resolves the type of the property from type of getter and setter.
 * @throws IntrospectionException if the property doesnt folow the design patterns
 * @return The type of the property.
 */
TypeMirror findPropertyType(CompilationInfo javac) throws IntrospectionException {

    TypeMirror resolvedType = null;

    if ( getterMethod != null ) {
        if ( !getterMethod.getParameters().isEmpty() ) {
            throw new IntrospectionException( "bad read method arg count" ); // NOI18N
        }
        resolvedType = getterMethod.getReturnType();
        if ( resolvedType.getKind() == TypeKind.VOID ) {                
            throw new IntrospectionException( "read method " + getterMethod.getSimpleName() + // NOI18N
                                              " returns void" ); // NOI18N
        }
    }
    
    if ( setterMethod != null ) {
        List<? extends VariableElement> params = setterMethod.getParameters();
        if ( params.size() != 1 ) {
            throw new IntrospectionException( "bad write method arg count" ); // NOI18N
        }
        VariableElement param = params.get(0);
        if ( resolvedType != null && !javac.getTypes().isSameType(resolvedType, param.asType()) ) {
            throw new IntrospectionException( "type mismatch between read and write methods" ); // NOI18N
        }
        resolvedType = param.asType();
    }
    return resolvedType;
}
 
Example 12
Source File: TypesImpl.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean isSameType(TypeMirror t1, TypeMirror t2) {
	if (t1.getKind() == TypeKind.WILDCARD || t2.getKind() == TypeKind.WILDCARD) {
        // Wildcard types are never equal, according to the spec of this method
		return false;
	}
    if (t1 == t2) {
        return true;
    }
    if (!(t1 instanceof TypeMirrorImpl) || !(t2 instanceof TypeMirrorImpl)) {
        return false;
    }
    Binding b1 = ((TypeMirrorImpl)t1).binding();
    Binding b2 = ((TypeMirrorImpl)t2).binding();

    if (b1 == b2) {
        return true;
    }
    if (!(b1 instanceof TypeBinding) || !(b2 instanceof TypeBinding)) {
        return false;
    }
    TypeBinding type1 = ((TypeBinding) b1);
    TypeBinding type2 = ((TypeBinding) b2);
    if (TypeBinding.equalsEquals(type1,  type2))
    	return true;
    return CharOperation.equals(type1.computeUniqueKey(), type2.computeUniqueKey());
}
 
Example 13
Source File: AnnotatedNonVolatileEntityClass.java    From Mnemonic with Apache License 2.0 5 votes vote down vote up
private long computeTypeSize(TypeMirror type) {
long ret;
switch (type.getKind()) {
case BYTE:
    ret = 1L;
    break;
case BOOLEAN:
    ret = 1L;
    break;
case CHAR:
    ret = 2L;
    break;
case DOUBLE:
    ret = 8L;
    break;
case FLOAT:
    ret = 4L;
    break;
case SHORT:
    ret = 2L;
    break;
case INT:
    ret = 4L;
    break;
case LONG:
    ret = 8L;
    break;
default:
    ret = 8L;
}
return ret;
   }
 
Example 14
Source File: JNIWriter.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
int dimensions(TypeMirror t) {
    if (t.getKind() != TypeKind.ARRAY)
        return 0;
    return 1 + dimensions(((ArrayType) t).getComponentType());
}
 
Example 15
Source File: TypeKey.java    From paperparcel with Apache License 2.0 4 votes vote down vote up
@Override boolean isMatch(Types types, TypeMirror type) {
  return type.getKind() == TypeKind.DECLARED
      && ((TypeElement)((DeclaredType) type).asElement())
      .getQualifiedName().contentEquals(name());
}
 
Example 16
Source File: CompileTimeTypeInfo.java    From picocli with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isEnum() {
    TypeMirror type = auxTypeMirrors.get(0);
    return type.getKind() == TypeKind.DECLARED &&
            ((DeclaredType) type).asElement().getKind() == ElementKind.ENUM;
}
 
Example 17
Source File: MoveMembersRefactoringPlugin.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private Problem compareMethodSignatures(ExecutableElement method, ExecutableElement exMethod, Element targetElement, CompilationInfo javac) {
    Problem p = null;
    if (!exMethod.equals(method)) {
        if (exMethod.getSimpleName().equals(method.getSimpleName())
                && exMethod.getParameters().size() == method.getParameters().size()) {
            boolean sameParameters = true;
            boolean wideningConversion = true;
            for (int j = 0; j < exMethod.getParameters().size(); j++) {
                TypeMirror exType = ((VariableElement) exMethod.getParameters().get(j)).asType();
                TypeMirror paramType = method.getParameters().get(j).asType();
                if (!javac.getTypes().isSameType(exType, paramType)) {
                    sameParameters = false;
                    if (exType.getKind().isPrimitive() && paramType.getKind().isPrimitive()) {
                        /*
                         * byte to short, int, long, float, or double
                         * short to int, long, float, or double
                         * char to int, long, float, or double
                         * int to long, float, or double
                         * long to float or double
                         * float to double
                         */
                        switch (exType.getKind()) {
                            case DOUBLE:
                                if (paramType.getKind().equals(TypeKind.FLOAT)) {
                                    break;
                                }
                            case FLOAT:
                                if (paramType.getKind().equals(TypeKind.LONG)) {
                                    break;
                                }
                            case LONG:
                                if (paramType.getKind().equals(TypeKind.INT)) {
                                    break;
                                }
                            case INT:
                                if (paramType.getKind().equals(TypeKind.SHORT)) {
                                    break;
                                }
                            case SHORT:
                                if (paramType.getKind().equals(TypeKind.BYTE)) {
                                    break;
                                }
                            case BYTE:
                                wideningConversion = false;
                                break;
                        }
                    } else {
                        wideningConversion = false;
                    }
                }
            }
            if (sameParameters) {
                p = createProblem(p, true, NbBundle.getMessage(ChangeParametersPlugin.class, "ERR_existingMethod", exMethod.toString(), ((TypeElement)targetElement).getQualifiedName())); // NOI18N
            } else if (wideningConversion) {
                p = createProblem(p, false, NbBundle.getMessage(ChangeParametersPlugin.class, "WRN_wideningConversion", exMethod.toString(), ((TypeElement)targetElement).getQualifiedName())); // NOI18N
            }
        }
    }
    
    return p;
}
 
Example 18
Source File: MoreTypes.java    From doma with Apache License 2.0 4 votes vote down vote up
public boolean isArray(TypeMirror typeMirror) {
  assertNotNull(typeMirror);
  return typeMirror.getKind() == TypeKind.ARRAY;
}
 
Example 19
Source File: ElementScanningTask.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/** Creates HTML display name of the Executable element */
private String createHtmlHeader(CompilationInfo info, ExecutableElement e, boolean isDeprecated,boolean isInherited, boolean fqn, TypeElement overridenFrom) {

    StringBuilder sb = new StringBuilder();
    if ( isDeprecated ) {
        sb.append("<s>"); // NOI18N
    }
    if( isInherited ) {
        sb.append( "<font color=" + ui.getInheritedColor() + ">" ); // NOI18N
    }
    Name name = e.getKind() == ElementKind.CONSTRUCTOR ? e.getEnclosingElement().getSimpleName() : e.getSimpleName();
    sb.append(Utils.escape(name.toString()));        
    if ( isDeprecated ) {
        sb.append("</s>"); // NOI18N
    }

    sb.append("("); // NOI18N

    List<? extends VariableElement> params = e.getParameters();
    for( Iterator<? extends VariableElement> it = params.iterator(); it.hasNext(); ) {
        VariableElement param = it.next(); 
        sb.append( "<font color=" + ui.getTypeColor() + ">" ); // NOI18N
        final boolean vararg = !it.hasNext() && e.isVarArgs();
        sb.append(printArg(info, param.asType(),vararg, fqn));
        sb.append("</font>"); // NOI18N
        sb.append(" "); // NOI18N
        sb.append(Utils.escape(param.getSimpleName().toString()));
        if ( it.hasNext() ) {
            sb.append(", "); // NOI18N
        }
    }


    sb.append(")"); // NOI18N

    if ( e.getKind() != ElementKind.CONSTRUCTOR ) {
        TypeMirror rt = e.getReturnType();
        if ( rt.getKind() != TypeKind.VOID ) {
            sb.append(" : "); // NOI18N
            sb.append( "<font color=" + ui.getTypeColor() + ">" ); // NOI18N
            sb.append(print(info, e.getReturnType(), fqn));
            sb.append("</font>"); // NOI18N
        }
    }

    if (!isInherited && overridenFrom != null) {
        sb.append(" ↑ ");   //NOI18N
        sb.append(print(info, overridenFrom.asType(), fqn));
    }

    return sb.toString();
}
 
Example 20
Source File: AttributeInfo.java    From dsl-json with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public AttributeInfo(
		String name,
		ExecutableElement readMethod,
		ExecutableElement writeMethod,
		@Nullable VariableElement field,
		TypeMirror type,
		boolean isList,
		boolean isSet,
		boolean isMap,
		AnnotationMirror annotation,
		boolean notNull,
		boolean mandatory,
		final int index,
		@Nullable String alias,
		boolean fullMatch,
		@Nullable CompiledJson.TypeSignature typeSignature,
		JsonAttribute.IncludePolicy includeToMinimal,
		@Nullable ConverterInfo converter,
		boolean isJsonObject,
		LinkedHashSet<TypeMirror> usedTypes,
		Map<String, Integer> typeVariablesIndex,
		boolean containsStructOwnerType) {
	this.id = alias != null ? alias : name;
	this.name = name;
	this.readMethod = readMethod;
	this.writeMethod = writeMethod;
	this.field = field;
	this.element = field != null ? field : readMethod;
	this.type = type;
	this.annotation = annotation;
	this.notNull = notNull;
	this.mandatory = mandatory;
	this.index = index;
	this.alias = alias;
	this.fullMatch = fullMatch;
	this.typeSignature = typeSignature;
	this.includeToMinimal = includeToMinimal;
	this.converter = converter;
	this.isJsonObject = isJsonObject;
	this.typeName = type.toString();
	this.readProperty = field != null ? field.getSimpleName().toString() : readMethod.getSimpleName() + "()";
	this.isArray = type.getKind() == TypeKind.ARRAY;
	this.isList = isList;
	this.isSet = isSet;
	this.isMap = isMap;
	this.usedTypes = usedTypes;
	this.typeVariablesIndex = typeVariablesIndex;
	this.isGeneric = !typeVariablesIndex.isEmpty();
	this.containsStructOwnerType = containsStructOwnerType;
}