Java Code Examples for javax.lang.model.type.TypeKind#ARRAY

The following examples show how to use javax.lang.model.type.TypeKind#ARRAY . 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: JavaElementHandler.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private List<String> getParameterListForMethod(ExecutableElement exe) {
    List<String> parameters = new ArrayList<String>();

    if (exe != null) {
        // generate a list of parameters
        // unfortunately, we have to work around # 139695 in an ugly fashion

        try {
            List<? extends VariableElement> params = exe.getParameters(); // this can cause NPE's

            for (VariableElement variableElement : params) {
                TypeMirror tm = variableElement.asType();

                if (tm.getKind() == TypeKind.DECLARED || tm.getKind() == TypeKind.ARRAY) {
                    parameters.add(GroovyUtils.stripPackage(tm.toString()));
                } else {
                    parameters.add(tm.toString());
                }
            }
        } catch (NullPointerException e) {
            // simply do nothing.
        }
    }
    return parameters;
}
 
Example 2
Source File: IntroduceLocalExtensionTransformer.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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 3
Source File: PreconditionsChecker.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private boolean isIterbale(ExpressionTree expression) {
    TypeMirror tm = workingCopy.getTrees().getTypeMirror(TreePath.getPath(workingCopy.getCompilationUnit(), expression));
    if (!Utilities.isValidType(tm)) {
        return false;
    }
    if (tm.getKind() == TypeKind.ARRAY) {
        return false;
    } else {
        tm = workingCopy.getTypes().erasure(tm);
        TypeElement typeEl = workingCopy.getElements().getTypeElement("java.util.Collection");
        if (typeEl != null) {
            TypeMirror collection = typeEl.asType();
            collection = workingCopy.getTypes().erasure(collection);
            if (this.workingCopy.getTypes().isSubtype(tm, collection)) {
                return true;
            }
        }
    }

    return false;
}
 
Example 4
Source File: ConfigDoItemFinder.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private String simpleTypeToString(TypeMirror typeMirror) {
    if (typeMirror.getKind().isPrimitive()) {
        return typeMirror.toString();
    } else if (typeMirror.getKind() == TypeKind.ARRAY) {
        return simpleTypeToString(((ArrayType) typeMirror).getComponentType());
    }

    final String knownGenericType = getKnownGenericType((DeclaredType) typeMirror);

    if (knownGenericType != null) {
        return knownGenericType;
    }

    List<? extends TypeMirror> typeArguments = ((DeclaredType) typeMirror).getTypeArguments();
    if (!typeArguments.isEmpty()) {
        return simpleTypeToString(typeArguments.get(0));
    }

    return typeMirror.toString();
}
 
Example 5
Source File: Getter.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Getter's underlying Java type.
 *
 * <p>The type is fully resolved with respect to generics, i.e. {@code Optional<MyType<String>>},
 * not {@code Optional<T>}.
 */
public TypeMirror getUnderlyingType() {
  if (returnType().getKind() != TypeKind.ARRAY) {
    return returnType();
  }
  return ((ArrayType) returnType()).getComponentType();
}
 
Example 6
Source File: JDIWrappersTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private TypeMirror adjustTypeMirror(TypeMirror tm) {
    if (tm.getKind() == TypeKind.EXECUTABLE) {
        tm = ((ExecutableType) tm).getReturnType();
        tm = adjustTypeMirror(tm);
    } else if (tm.getKind() == TypeKind.ARRAY) {
        tm = ((ArrayType) tm).getComponentType();
        tm = adjustTypeMirror(tm);
    }
    return tm;
}
 
Example 7
Source File: Bundler.java    From easybundler with Apache License 2.0 5 votes vote down vote up
/**
 * See {@link #matchesArrayClass(VariableElement, Class, MatchPolicy)}.
 */
private boolean matchesArrayClass(VariableElement field, String className, MatchPolicy policy) {
    // Check if the field is an array
    if (field.asType().getKind() != TypeKind.ARRAY) {
        return false;
    }

    // Get the type of array it is
    TypeMirror componentType = ((ArrayType) field.asType()).getComponentType();

    // Perform check
    TypeElement target = getTypeElementForClass(className);
    return target != null && typesMatch(componentType, target.asType(), policy);
}
 
Example 8
Source File: JniProcessor.java    From cronet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
TypeName toTypeName(TypeMirror t, boolean useJni) {
    if (t.getKind() == TypeKind.ARRAY) {
        return ArrayTypeName.of(toTypeName(((ArrayType) t).getComponentType(), useJni));
    }
    TypeName typeName = TypeName.get(t);
    if (useJni && shouldDowncastToObjectForJni(typeName)) {
        return TypeName.OBJECT;
    }
    return typeName;
}
 
Example 9
Source File: ElementNode.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static String createHtmlHeader(boolean deprecated, ExecutableElement e) {
    StringBuilder sb = new StringBuilder();
    sb.append("<html>");
    if (deprecated) sb.append("<s>");
    if (e.getKind() == ElementKind.CONSTRUCTOR) {
        sb.append(e.getEnclosingElement().getSimpleName());
    } else {
        sb.append(e.getSimpleName());
    }
    if (deprecated) sb.append("</s>");
    sb.append("("); // NOI18N
    for(Iterator<? extends VariableElement> it = e.getParameters().iterator(); it.hasNext(); ) {
        VariableElement param = it.next();
        if (!it.hasNext() && e.isVarArgs() && param.asType().getKind() == TypeKind.ARRAY) {
            sb.append(translateToHTML(print(((ArrayType) param.asType()).getComponentType())));
            sb.append("...");
        } else {
            sb.append(translateToHTML(print(param.asType())));
        }
        sb.append(" "); // NOI18N
        sb.append(param.getSimpleName());
        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(translateToHTML(print(e.getReturnType())));
        }
    }
    return sb.toString();
}
 
Example 10
Source File: AttributeBuilderReflection.java    From immutables with Apache License 2.0 5 votes vote down vote up
/**
 * Return true if the possibleBuilderMethod matches the
 * Style#attributeBuilder() and returns a class.
 *
 * TODO: may need to make this return true if the return type is an interface too...
 *
 * @param possibleBuilderMethod executableElement
 */
private static boolean isPossibleBuilderMethod(Element possibleBuilderMethod, boolean onValueType, ValueAttribute valueAttribute) {
  if (possibleBuilderMethod.getKind() == ElementKind.METHOD) {
    if (!valueAttribute.containingType.names().possibleAttributeBuilder(possibleBuilderMethod.getSimpleName())) {
      return false;
    }

    ExecutableElement candidateMethod = (ExecutableElement) possibleBuilderMethod;

    TypeKind kind = candidateMethod.getReturnType().getKind();

    return possibleBuilderMethod.getModifiers().containsAll(
        Arrays.asList(Modifier.STATIC, Modifier.PUBLIC))
        && candidateMethod.getParameters().isEmpty()
        && candidateMethod.getReturnType().getKind() == TypeKind.DECLARED
        && !kind.isPrimitive() && kind != TypeKind.ARRAY;

  } else if (!onValueType && possibleBuilderMethod.getKind() == ElementKind.CONSTRUCTOR) {
    if (!valueAttribute.containingType.names().newTokenInAttributeBuilder()) {
      return false;
    }

    ExecutableElement candidateConstructor = (ExecutableElement) possibleBuilderMethod;

    return candidateConstructor.getModifiers().contains(Modifier.PUBLIC)
        && candidateConstructor.getTypeParameters().isEmpty();
  }
  return false;
}
 
Example 11
Source File: ELTypeUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Whether the given node represents static {@link Iterable} field where can be used operators.
 * @param ccontext compilation context
 * @param element element to examine
 * @return {@code true} if the object is static {@link Iterable} field, {@code false} otherwise
 * @since 1.26
 */
public static boolean isIterableElement(CompilationContext ccontext, Element element) {
    if (element.getKind() == ElementKind.CLASS) {
        return isSubtypeOf(ccontext, element.asType(), "java.lang.Iterable"); //NOI18N
    } else if (element.getKind() == ElementKind.METHOD) {
        TypeMirror returnType = ELTypeUtilities.getReturnType(ccontext, (ExecutableElement) element);
        if (returnType.getKind() == TypeKind.ARRAY
                || isSubtypeOf(ccontext, returnType, "java.lang.Iterable")) { //NOI18N
            return true;
        }
    } else if (element.getKind() == ElementKind.INTERFACE) {
        return isSubtypeOf(ccontext, element.asType(), "java.lang.Iterable"); //NOI18N
    }
    return false;
}
 
Example 12
Source File: CreateElementUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static List<? extends TypeMirror> computeNewArray(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
    NewArrayTree nat = (NewArrayTree) parent.getLeaf();
    
    if (nat.getType() == error) {
        types.add(ElementKind.CLASS);
        types.add(ElementKind.ENUM);
        types.add(ElementKind.INTERFACE);
        
        return null;
    }
    
    for (Tree dimension : nat.getDimensions()) {
        if (dimension == error) {
            types.add(ElementKind.PARAMETER);
            types.add(ElementKind.LOCAL_VARIABLE);
            types.add(ElementKind.FIELD);
            
            return Collections.singletonList(info.getTypes().getPrimitiveType(TypeKind.INT));
        }
    }
    
    for (Tree init : nat.getInitializers()) {
        if (init == error) {
            TypeMirror whole = info.getTrees().getTypeMirror(parent);
            
            if (whole == null || whole.getKind() != TypeKind.ARRAY)
                return null;
            
            types.add(ElementKind.PARAMETER);
            types.add(ElementKind.LOCAL_VARIABLE);
            types.add(ElementKind.FIELD);
            
            return Collections.singletonList(((ArrayType) whole).getComponentType());
        }
    }
    
    return null;
}
 
Example 13
Source File: TypeDesc.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static String encodeAsString(TypeDesc td) {
    if (td.typeKind.isPrimitive() || td.typeKind == TypeKind.VOID)
        return StringUtils.toLowerCase(td.typeKind.toString());

    if (td.typeKind == TypeKind.ARRAY)
        return encodeAsString(((ArrayTypeDesc) td).compTypeDesc) + "[]";

    if (td.typeKind == TypeKind.TYPEVAR)
        return "#" + ((TypeVarTypeDesc) td).identifier;

    if (td.typeKind == TypeKind.DECLARED)
        return ((ReferenceTypeDesc) td).javaType.toString();

    throw new AssertionError("Unhandled type: " + td.typeKind);
}
 
Example 14
Source File: ASTPathCriterion.java    From annotation-tools with MIT License 4 votes vote down vote up
private boolean checkReceiverType(int i, Type t) {
    if (t == null) { return false; }
    while (++i < astPath.size()) {
        ASTPath.ASTEntry entry = astPath.get(i);
        switch (entry.getTreeKind()) {
        case ANNOTATED_TYPE:
          break;
        case ARRAY_TYPE:
          if (t.getKind() != TypeKind.ARRAY) { return false; }
          t = ((Type.ArrayType) t).getComponentType();
          break;
        case MEMBER_SELECT:
          // TODO
          break;
        case PARAMETERIZED_TYPE:
          if (entry.childSelectorIs(ASTPath.TYPE_PARAMETER)) {
            if (!t.isParameterized()) { return false; }
            List<Type> args = t.getTypeArguments();
            int a = entry.getArgument();
            if (a >= args.size()) { return false; }
            t = args.get(a);
          } // else TYPE -- stay?
          break;
        case TYPE_PARAMETER:
          if (t.getKind() != TypeKind.WILDCARD) { return false; }
          t = t.getLowerBound();
          break;
        case EXTENDS_WILDCARD:
          if (t.getKind() != TypeKind.WILDCARD) { return false; }
          t = ((Type.WildcardType) t).getExtendsBound();
          break;
        case SUPER_WILDCARD:
          if (t.getKind() != TypeKind.WILDCARD) { return false; }
          t = ((Type.WildcardType) t).getSuperBound();
          break;
        case UNBOUNDED_WILDCARD:
          if (t.getKind() != TypeKind.WILDCARD) { return false; }
          t = t.getLowerBound();
          break;
        default:
          return false;
        }
        if (t == null) { return false; }
    }
    return true;
}
 
Example 15
Source File: JNIWriter.java    From openjdk-8 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 16
Source File: SourceModeler.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private RestEntity getRestEntity( CompilationController controller,
        Collection<TypeMirror> boxedPrimitives, TypeMirror typeMirror )
{
    if ( typeMirror.getKind() == TypeKind.VOID ){
        return new RestEntity( true );
    }
    String entityFqn = null;
    boolean isCollection = false;
    boolean isPrimitive = false;
    if ( controller.getTypes().isSubtype( controller.getTypes().erasure(typeMirror), 
            controller.getTypes().erasure(controller.getElements().getTypeElement(
                    Collection.class.getCanonicalName()).asType())) )
    {
        isCollection = true;
        List<? extends TypeMirror> typeArguments = 
            ((DeclaredType)typeMirror).getTypeArguments();
        
        if ( typeArguments.size() != 0 ){
            // There should be only one parameter
            TypeMirror typeArg = typeArguments.get( 0 );
            entityFqn = getQualifiedName(controller, typeArg);
        }
    }
    else if ( typeMirror.getKind() == TypeKind.ARRAY ){
        isCollection = true;
        TypeMirror componentType = ((ArrayType)typeMirror).
            getComponentType();
        entityFqn = getQualifiedName(controller, componentType);
    }
    if ( typeMirror.getKind().isPrimitive() || 
            controller.getTypes().isSameType(typeMirror, 
                    controller.getElements().
                    getTypeElement(String.class.getCanonicalName()).asType()))
    {
        isPrimitive = true;
    }
    else {
        for ( TypeMirror boxed: boxedPrimitives ){
            if ( controller.getTypes().isSameType(typeMirror, boxed)){
                isPrimitive = true;
                break;
            }
        }
    }
    if ( !isCollection && !isPrimitive ){
        entityFqn = getQualifiedName(controller, typeMirror );
    }
    if ( entityFqn== null ){
        entityFqn = Object.class.getCanonicalName();
    }
    
    if ( isPrimitive){
        return new RestEntity( false );
    }
    return new RestEntity( entityFqn, isCollection );
}
 
Example 17
Source File: Utils.java    From netbeans with Apache License 2.0 4 votes vote down vote up
static void formatTypeMirror( TypeMirror typeMirror,
        StringBuilder stringBuilder, boolean FQNs )
{
    if (typeMirror == null) {
        return;
    }

    switch (typeMirror.getKind()) {
        case BOOLEAN:
        case BYTE:
        case CHAR:
        case DOUBLE:
        case FLOAT:
        case INT:
        case LONG:
        case NONE:
        case NULL:
        case SHORT:
        case VOID:
            stringBuilder.append(typeMirror);

            break;

        case TYPEVAR:
            TypeVariable typeVariable = (TypeVariable) typeMirror;
            stringBuilder.append(typeVariable.asElement().getSimpleName()
                    .toString());
            break;

        case WILDCARD:
            WildcardType wildcardType = (WildcardType) typeMirror;
            stringBuilder.append("?");
            if (wildcardType.getExtendsBound() != null) {
                stringBuilder.append(" extends "); // NOI18N
                formatTypeMirror(wildcardType.getExtendsBound(),
                        stringBuilder, FQNs);
            }
            if (wildcardType.getSuperBound() != null) {
                stringBuilder.append(" super "); // NOI18N
                formatTypeMirror(wildcardType.getSuperBound(),
                        stringBuilder, FQNs);
            }

            break;

        case DECLARED:
            DeclaredType declaredType = (DeclaredType) typeMirror;
            Element element = declaredType.asElement();
            if (element instanceof TypeElement) {
                stringBuilder.append(FQNs ? ((TypeElement) element)
                        .getQualifiedName().toString() : element
                        .getSimpleName().toString());
            }
            else {
                stringBuilder.append(element.getSimpleName().toString());
            }
            List<? extends TypeMirror> typeArgs = declaredType
                    .getTypeArguments();
            if (!typeArgs.isEmpty()) {
                stringBuilder.append("<");
                formatTypeMirrors(typeArgs, stringBuilder, FQNs);
                stringBuilder.append(">");
            }

            break;

        case ARRAY:

            int dims = 0;

            while (typeMirror.getKind() == TypeKind.ARRAY) {
                dims++;
                typeMirror = ((ArrayType) typeMirror).getComponentType();
            }

            formatTypeMirror(typeMirror, stringBuilder, FQNs);

            for (int i = 0; i < dims; i++) {
                stringBuilder.append("[]");
            }

            break;
    }
}
 
Example 18
Source File: ArrayTypeDesc.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public ArrayTypeDesc(TypeDesc compTypeDesc) {
    super(TypeKind.ARRAY);
    this.compTypeDesc = compTypeDesc;
}
 
Example 19
Source File: ArrayTypeImpl.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public TypeKind getKind() {
	return TypeKind.ARRAY;
}
 
Example 20
Source File: ConfusingVarargsParameter.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@TriggerPatterns({
    @TriggerPattern(value="$methodName($vars$, $v)", constraints = @ConstraintVariableType(variable = "$v", type = "int[]")),
    @TriggerPattern(value="$methodName($vars$, $v)", constraints = @ConstraintVariableType(variable = "$v", type = "boolean[]")),
    @TriggerPattern(value="$methodName($vars$, $v)", constraints = @ConstraintVariableType(variable = "$v", type = "byte[]")),
    @TriggerPattern(value="$methodName($vars$, $v)", constraints = @ConstraintVariableType(variable = "$v", type = "short[]")),
    @TriggerPattern(value="$methodName($vars$, $v)", constraints = @ConstraintVariableType(variable = "$v", type = "char[]")),
    @TriggerPattern(value="$methodName($vars$, $v)", constraints = @ConstraintVariableType(variable = "$v", type = "long[]")),
    @TriggerPattern(value="$methodName($vars$, $v)", constraints = @ConstraintVariableType(variable = "$v", type = "float[]")),
    @TriggerPattern(value="$methodName($vars$, $v)", constraints = @ConstraintVariableType(variable = "$v", type = "double[]")),

    @TriggerPattern(value="new $className($vars$, $v)", constraints = @ConstraintVariableType(variable = "$v", type = "int[]")),
    @TriggerPattern(value="new $className($vars$, $v)", constraints = @ConstraintVariableType(variable = "$v", type = "boolean[]")),
    @TriggerPattern(value="new $className($vars$, $v)", constraints = @ConstraintVariableType(variable = "$v", type = "byte[]")),
    @TriggerPattern(value="new $className($vars$, $v)", constraints = @ConstraintVariableType(variable = "$v", type = "short[]")),
    @TriggerPattern(value="new $className($vars$, $v)", constraints = @ConstraintVariableType(variable = "$v", type = "char[]")),
    @TriggerPattern(value="new $className($vars$, $v)", constraints = @ConstraintVariableType(variable = "$v", type = "long[]")),
    @TriggerPattern(value="new $className($vars$, $v)", constraints = @ConstraintVariableType(variable = "$v", type = "float[]")),
    @TriggerPattern(value="new $className($vars$, $v)", constraints = @ConstraintVariableType(variable = "$v", type = "double[]"))
})
@Hint(
        displayName = "#DN_ConfusingVarargsArray",
        description = "#DESCR_ConfusingVarargsArray",
        enabled = true,
        category = "bugs",
        suppressWarnings = { "ConfusingArrayVararg", "PrimitiveArrayArgumentToVariableArgMethod" }
)
public static ErrorDescription primitiveArray(HintContext ctx) {
    TreePath invPath = ctx.getPath();
    CompilationInfo ci = ctx.getInfo();
    if (!isVarargsParameter(ci, invPath)) {
        return null;
    }
    MethodInvocationTree mit = (MethodInvocationTree)invPath.getLeaf();
    ExpressionTree arg = mit.getArguments().get(mit.getArguments().size() - 1);
    if (arg.getKind() == Tree.Kind.NULL_LITERAL) {
        return null;
    }
    // suppress on classes covered by ArrayStringConversions
    Element e = ci.getTrees().getElement(invPath);
    if (e != null) {
        if (e.getKind() == ElementKind.CONSTRUCTOR || e.getKind() == ElementKind.METHOD) {
            VariableElement var = ((ExecutableElement)e).getParameters().get(mit.getArguments().size() - 1);
            TypeKind tk = var.asType().getKind();
            if (tk == TypeKind.ARRAY) {
                TypeMirror tm = ((ArrayType)var.asType()).getComponentType();
                if (tm.getKind().isPrimitive()) {
                    return null;
                }
            }
        }
        Element ecl = e.getEnclosingElement();
        if (ecl != null && (ecl.getKind().isClass() || ecl.getKind().isInterface())) {
            TypeElement te = (TypeElement)ecl;
            String qn = te.getQualifiedName().toString();
            for (String s : EXCLUDE_CLASSES) {
                if (s.equals(qn)) {
                    return null;
                }
            }
        }
    }
    return ErrorDescriptionFactory.forTree(ctx,
            mit.getArguments().get(mit.getArguments().size() - 1),
            Bundle.TEXT_ConfusingPrimitveArrayToVararg());
}