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

The following are top voted examples for showing how to use javax.lang.model.type.PrimitiveType. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: incubator-netbeans   File: ControllerGenerator.java   View source code 6 votes vote down vote up
/**
 * Defines a new method as event handler, and marks it with @FXML annotation.
 * 
 * @param h handler definition
 */
private void defineNewHandler(CharSequence handlerName, TypeElement eventType) {
    TreeMaker mk = wcopy.getTreeMaker();
    
    // @FXML private void {handlerName}({eventType} event);
    MethodTree handler = mk.Method(
            mk.Modifiers(Collections.singleton(Modifier.PRIVATE), 
                Collections.singletonList(fxmlAnnotationTree)
            ),
            handlerName, 
            mk.PrimitiveType(TypeKind.VOID),
            Collections.<TypeParameterTree>emptyList(),
            Collections.singletonList(
                mk.Variable(
                    mk.Modifiers(Collections.<Modifier>emptySet()), 
                    "event", mk.Type(eventType.asType()), null)
            ), 
            Collections.<ExpressionTree>emptyList(),
            mk.Block(Collections.<StatementTree>emptyList(), false), 
            null);
    
    // add to class
    controllerClass = genUtils().insertClassMember(controllerClass, handler);
    addMethod(handlerName.toString(), eventType.asType());
}
 
Example 2
Project: incubator-netbeans   File: PreconditionsChecker.java   View source code 6 votes vote down vote up
@Override
public Tree visitIdentifier(IdentifierTree that, Trees trees) {

    TypeMirror type = trees.getTypeMirror(this.getCurrentPath());
    if (type == null /* will work even with error types || type.getKind() == TypeKind.ERROR */) {
        return super.visitIdentifier(that, trees);
    }
    if (type.getKind().isPrimitive()) {
        this.varToType.put(that.getName(), workingCopy.getTypes().boxedClass((PrimitiveType) type).toString());
    } else {
        this.varToType.put(that.getName(), type.toString());
    }
    TreePath currentTreePath = this.getCurrentPath();
    Element el = trees.getElement(currentTreePath);
    if (el != null && isExternalNEF(el, that)) {
        checkIfRefactorableMutation(currentTreePath, that);
    }
    return super.visitIdentifier(that, trees);
}
 
Example 3
Project: incubator-netbeans   File: ReplaceBufferByString.java   View source code 6 votes vote down vote up
/**
 * Turns the argPath leaf expression to Wrapper.toString(arg) for primitives, or to String.valueOf(arg) for
 * object types. String.valueOf is null-safe.
 */
private ExpressionTree makeToString(TreePath argPath) {
    ExpressionTree arg = (ExpressionTree)argPath.getLeaf();
    TypeMirror tm = wc.getTrees().getTypeMirror(argPath);
    if (isPrimitiveType(tm)) {
        // call WrapperType.toString(arg)
        arg = mk.MethodInvocation(
            Collections.<ExpressionTree>emptyList(),
            mk.MemberSelect(
                mk.QualIdent(wc.getTypes().boxedClass((PrimitiveType)tm)), 
                "toString" // NOI18N
            ), Collections.singletonList(arg));
    } else {
        arg = mk.MethodInvocation(
            Collections.<ExpressionTree>emptyList(),
            mk.MemberSelect(
                mk.QualIdent(stringType.asElement()),
                "valueOf" // NOI18N
            ), Collections.singletonList(arg)
        );
    }

    return arg;
}
 
Example 4
Project: incubator-netbeans   File: ExpectedTypeResolver.java   View source code 6 votes vote down vote up
@Override
public List<? extends TypeMirror> visitEnhancedForLoop(EnhancedForLoopTree node, Object p) {
    TypeMirror varType = info.getTrees().getTypeMirror(new TreePath(getCurrentPath(), node.getVariable()));
    if (!Utilities.isValidType(varType)) {
        return null;
    } else {
        TypeMirror arrayType = info.getTypes().getArrayType(varType);
        TypeElement iterableEl = info.getElements().getTypeElement("java.lang.Iterable"); // NOI18N
        if (iterableEl == null || iterableEl.getKind() != ElementKind.INTERFACE) {
            return null;
        }
        TypeMirror iterableForVar = isPrimitiveType(varType.getKind()) ?
                info.getTypes().getDeclaredType(iterableEl, 
                    info.getTypes().getWildcardType(
                        info.getTypes().boxedClass((PrimitiveType)varType).asType(), null))
                :
                info.getTypes().getDeclaredType(iterableEl, 
                    info.getTypes().getWildcardType(varType, null)
                );
        List<TypeMirror> result = new ArrayList<TypeMirror>(2);
        result.add(arrayType);
        result.add(iterableForVar);
        return result;
    }
}
 
Example 5
Project: Witch-Android   File: TypeUtils.java   View source code 6 votes vote down vote up
public TypeName getValueType(Element value) {

        TypeMirror type = getType(value);

        // Box if primitive
        if(type.getKind() != null && type.getKind().isPrimitive()) {
            type = types.boxedClass((PrimitiveType) type).asType();
        }

        // Get generic type if value container
        if(isValueContainer(type)) {
            DeclaredType declaredType = (DeclaredType) type;
            TypeMirror genericParameter = declaredType.getTypeArguments().get(0);
            return TypeName.get(genericParameter);
        }

        return TypeName.get(type);
    }
 
Example 6
Project: openjdk-jdk10   File: TypeMonikerFactory.java   View source code 6 votes vote down vote up
public static TypeMoniker getTypeMoniker(TypeMirror typeMirror) {
    if (typeMirror == null)
        throw new NullPointerException();

    if (typeMirror.getKind().isPrimitive())
        return new PrimitiveTypeMoniker((PrimitiveType) typeMirror);
    else if (typeMirror.getKind().equals(TypeKind.ARRAY))
        return new ArrayTypeMoniker((ArrayType) typeMirror);
    else if (typeMirror.getKind().equals(TypeKind.DECLARED))
        return new DeclaredTypeMoniker((DeclaredType) typeMirror);
    return getTypeMoniker(typeMirror.toString());
}
 
Example 7
Project: boomerang   File: BoomerangContext.java   View source code 6 votes vote down vote up
public boolean isValidQuery(AccessGraph ap, Unit stmt) {
  SootMethod m = bwicfg.getMethodOf(stmt);
  if (!ap.isStatic() && !m.getActiveBody().getLocals().contains(ap.getBase())) {
    return false;
  }

  if (ap.getBase() instanceof PrimitiveType) {
    return false;
  }
  if (!ap.isStatic() && !m.isStatic()) {
    Local thisLocal = m.getActiveBody().getThisLocal();
    if (ap.baseMatches(thisLocal)) {
      if (!ForwardFlowFunctions.hasCompatibleTypesForCall(ap, m.getDeclaringClass())) {
        return false;
      }
    }
  }
  return true;
}
 
Example 8
Project: boomerang   File: BoomerangContext.java   View source code 6 votes vote down vote up
public void validateInput(AccessGraph ap, Unit stmt) {
  SootMethod m = bwicfg.getMethodOf(stmt);
  if (!ap.isStatic() && !m.getActiveBody().getLocals().contains(ap.getBase())) {
    throw new IllegalArgumentException("Base value of access path " + ap
        + " is not a local of the Method at which the Query was asked!");
  }
  if (stmt == null)
    throw new IllegalArgumentException("Statment must not be null");

  if (ap.getBase() instanceof PrimitiveType) {
    throw new IllegalArgumentException("The queried variable is not of pointer type");
  }
  if (!ap.isStatic() && !m.isStatic()) {
    Local thisLocal = m.getActiveBody().getThisLocal();
    if (ap.baseMatches(thisLocal)) {
      if (!ForwardFlowFunctions.hasCompatibleTypesForCall(ap, m.getDeclaringClass())) {
        throw new IllegalArgumentException("The type is incompatible");
      }
    }
  }
}
 
Example 9
Project: aidl2   File: Writer.java   View source code 6 votes vote down vote up
private Strategy getWrapperTypeStrategy(DeclaredType type) {
    final CharSequence name = Util.getQualifiedName(type);
    if (name != null) {
        switch (name.toString()) {
            case "java.lang.Boolean":
            case "java.lang.Byte":
            case "java.lang.Short":
            case "java.lang.Integer":
            case "java.lang.Long":
            case "java.lang.Character":
            case "java.lang.Float":
            case "java.lang.Double":
                // Handle Integer, Long, Character etc. before falling back to Serializable path
                final PrimitiveType primitiveVariety = types.unboxedType(type);

                if (primitiveVariety != null) {
                    return Strategy.create((b, n, t) -> writePrimitive(b, n, primitiveVariety), type);
                }
                break;
            case "java.lang.Void":
                return VOID_STRATEGY;
        }
    }

    return null;
}
 
Example 10
Project: aidl2   File: Writer.java   View source code 6 votes vote down vote up
private Strategy getArrayStrategy(ArrayType arrayType) throws CodegenException {
    final TypeMirror component = arrayType.getComponentType();
    final TypeKind componentKind = component.getKind();

    switch (componentKind) {
        case BOOLEAN:
        case INT:
        case SHORT:
        case BYTE:
        case CHAR:
        case LONG:
        case DOUBLE:
        case FLOAT:
            return getPrimitiveArrayStrategy((PrimitiveType) component);
        default:
            final Strategy strategy = getStrategy(component);

            if (strategy != null) {
                return isSerialStrategy(strategy) ? getSerializableStrategy() : getSpecialArrayStrategy(strategy, component);
            }
    }

    throw new CodegenException("Unsupported array component type: " + component + ".\n" + getHelpText());
}
 
Example 11
Project: aidl2   File: Writer.java   View source code 6 votes vote down vote up
private void writePrimitive(CodeBlock.Builder builder, Object name, PrimitiveType type) {
    switch (type.getKind()) {
        case LONG:
            builder.addStatement("$N.writeLong($L)", parcelName, name);
            break;
        case DOUBLE:
            builder.addStatement("$L.writeDouble($L)", parcelName, name);
            break;
        case FLOAT:
            builder.addStatement("$L.writeFloat($L)", parcelName, name);
            break;
        case BOOLEAN:
            builder.addStatement("$L.writeInt($L ? 1 : 0)", parcelName, name);
            break;
        default:
            builder.addStatement("$L.writeInt($L)", parcelName, name);
            break;
    }
}
 
Example 12
Project: aidl2   File: Reader.java   View source code 6 votes vote down vote up
private Strategy getWrapperTypeStrategy(DeclaredType type) {
    final CharSequence name = getQualifiedName(type);
    if (name != null) {
        switch (name.toString()) {
            case "java.lang.Boolean":
            case "java.lang.Byte":
            case "java.lang.Short":
            case "java.lang.Integer":
            case "java.lang.Long":
            case "java.lang.Character":
            case "java.lang.Float":
            case "java.lang.Double":
                // Handle Integer, Long, Character etc. before falling back to Serializable path
                final PrimitiveType primitiveVariety = types.unboxedType(type);

                if (primitiveVariety != null) {
                    return newStrategy($ -> readPrimitive(primitiveVariety), primitiveVariety);
                }
                break;
            case "java.lang.Void":
                return VOID_STRATEGY;
        }
    }

    return null;
}
 
Example 13
Project: aidl2   File: Reader.java   View source code 6 votes vote down vote up
private Strategy getArrayStrategy(ArrayType arrayType) throws CodegenException {
    final TypeMirror component = arrayType.getComponentType();
    final TypeKind componentKind = component.getKind();

    switch (componentKind) {
        case BOOLEAN:
        case INT:
        case SHORT:
        case BYTE:
        case CHAR:
        case LONG:
        case DOUBLE:
        case FLOAT:
            return getPrimitiveArrayStrategy((PrimitiveType) component);
        default:
            final Strategy strategy = getStrategy(component);

            if (strategy != null) {
                return isSerialStrategy(strategy)
                        ? getSerializableStrategy(types.getArrayType(component))
                        : getSpecialArrayStrategy(strategy, component);
            }
    }

    throw new CodegenException("Unsupported array component type: " + component + ".\n" + getHelpText());
}
 
Example 14
Project: aidl2   File: Reader.java   View source code 6 votes vote down vote up
private CodeBlock readPrimitive(PrimitiveType type) {
    switch (type.getKind()) {
        case LONG:
            return literal("$N.readLong()", parcelName);
        case DOUBLE:
            return literal("$N.readDouble()", parcelName);
        case FLOAT:
            return literal("$N.readFloat()", parcelName);
        case BOOLEAN:
            return literal("$N.readInt() == 1", parcelName);
        case INT:
            return literal("$N.readInt()", parcelName);
        default:
            return literal("($T) $N.readInt()", type, parcelName);
    }
}
 
Example 15
Project: Akatsuki   File: PrimitiveTypeAnalyzer.java   View source code 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 16
Project: FreeBuilder   File: Analyser.java   View source code 6 votes vote down vote up
/**
 * Introspects {@code method}, as found on {@code valueType}.
 */
private void addPropertyData(
    Property.Builder propertyBuilder,
    TypeElement valueType,
    ExecutableElement method,
    Optional<JacksonSupport> jacksonSupport) {
  TypeMirror propertyType = getReturnType(valueType, method, types);
  propertyBuilder
      .setAllCapsName(camelCaseToAllCaps(propertyBuilder.getName()))
      .setType(propertyType)
      .setFullyCheckedCast(CAST_IS_FULLY_CHECKED.visit(propertyType));
  if (jacksonSupport.isPresent()) {
    jacksonSupport.get().addJacksonAnnotations(propertyBuilder, method);
  }
  if (propertyType.getKind().isPrimitive()) {
    PrimitiveType unboxedType = types.getPrimitiveType(propertyType.getKind());
    TypeMirror boxedType = types.erasure(types.boxedClass(unboxedType).asType());
    propertyBuilder.setBoxedType(boxedType);
  }
}
 
Example 17
Project: bsoneer   File: TypeResolver.java   View source code 6 votes vote down vote up
@Override
public String visitPrimitive(PrimitiveType t, Void p) {
	switch (t.getKind()) {
	case BOOLEAN:
		return Boolean.class.getName();
	case BYTE:
		return Byte.class.getName();
	case CHAR:
		return Character.class.getName();
	case DOUBLE:
		return Double.class.getName();
	case FLOAT:
		return Float.class.getName();
	case INT:
		return Integer.class.getName();
	case LONG:
		return Long.class.getName();
	case SHORT:
		return Short.class.getName();
	default:
		throw new IllegalStateException();
	}
}
 
Example 18
Project: java-types   File: AbstractTypesContract.java   View source code 6 votes vote down vote up
private PrimitiveType primitiveType(Class<?> clazz) {
    assert clazz.isPrimitive();

    if (clazz.equals(double.class)) {
        return types.getPrimitiveType(TypeKind.DOUBLE);
    } else if (clazz.equals(float.class)) {
        return types.getPrimitiveType(TypeKind.FLOAT);
    } else if (clazz.equals(long.class)) {
        return types.getPrimitiveType(TypeKind.LONG);
    } else if (clazz.equals(int.class)) {
        return types.getPrimitiveType(TypeKind.INT);
    } else if (clazz.equals(short.class)) {
        return types.getPrimitiveType(TypeKind.SHORT);
    } else if (clazz.equals(byte.class)) {
        return types.getPrimitiveType(TypeKind.BYTE);
    } else if (clazz.equals(boolean.class)) {
        return types.getPrimitiveType(TypeKind.BOOLEAN);
    } else if (clazz.equals(char.class)) {
        return types.getPrimitiveType(TypeKind.CHAR);
    } else {
        throw new IllegalArgumentException(String.format("Unexpected primitive type: %s", clazz));
    }
}
 
Example 19
Project: java-types   File: AbstractTypesContract.java   View source code 6 votes vote down vote up
/**
 * Verifies {@link AbstractTypes#capture(TypeMirror)}.
 */
@Test
public void capture() {
    assertEquals(types.capture(type(Integer.class)), type(Integer.class));

    DeclaredType outerClassType = types.getDeclaredType(element(OuterClass.class), type(Integer.class));
    DeclaredType arrayListOfIntegersType = types.getDeclaredType(element(ArrayList.class), type(Integer.class));
    // innerClassType: OuterClass<Integer>.InnerClass<? extends ArrayList<Integer>>
    DeclaredType innerClassType = types.getDeclaredType(
        outerClassType,
        element(OuterClass.InnerClass.class),
        types.getWildcardType(arrayListOfIntegersType, null)
    );

    DeclaredType capturedType = (DeclaredType) types.capture(innerClassType);
    TypeVariable actualTypeArgument = (TypeVariable) capturedType.getTypeArguments().get(0);

    // intersectionType = glb(ArrayList<Integer>, List<?>, Serializable)
    IntersectionType intersectionType = (IntersectionType) actualTypeArgument.getUpperBound();
    assertTrue(isSubtypeOfOneOf(arrayListOfIntegersType, intersectionType.getBounds()));

    PrimitiveType intType = types.getPrimitiveType(TypeKind.INT);
    assertTrue(types.isSameType(types.capture(intType), intType));
}
 
Example 20
Project: doma   File: WrapperCtType.java   View source code 6 votes vote down vote up
@Override
public Class<?> visitPrimitive(PrimitiveType t, Void p) {
    switch (t.getKind()) {
    case BOOLEAN:
        return BooleanWrapper.class;
    case BYTE:
        return ByteWrapper.class;
    case SHORT:
        return ShortWrapper.class;
    case INT:
        return IntegerWrapper.class;
    case LONG:
        return LongWrapper.class;
    case FLOAT:
        return FloatWrapper.class;
    case DOUBLE:
        return DoubleWrapper.class;
    case CHAR:
        return null;
    default:
        return assertUnreachable();
    }
}
 
Example 21
Project: Glowplug   File: Util.java   View source code 6 votes vote down vote up
private static Class<?> box(PrimitiveType primitiveType) {
  switch (primitiveType.getKind()) {
    case BYTE:
      return Byte.class;
    case SHORT:
      return Short.class;
    case INT:
      return Integer.class;
    case LONG:
      return Long.class;
    case FLOAT:
      return Float.class;
    case DOUBLE:
      return Double.class;
    case BOOLEAN:
      return Boolean.class;
    case CHAR:
      return Character.class;
    case VOID:
      return Void.class;
    default:
      throw new AssertionError();
  }
}
 
Example 22
Project: incubator-netbeans   File: BeanModelBuilder.java   View source code 5 votes vote down vote up
private void addConstant(VariableElement v) {
    Set<Modifier> mods = v.getModifiers();
    if (!(mods.contains(Modifier.FINAL) && mods.contains(Modifier.STATIC))) {
        return;
    }
    
    boolean ok = false;
    
    // check that the return type is the same as this class' type
    if (!compilationInfo.getTypes().isSameType(
            v.asType(), classElement.asType())) {
        // the constant may be primitive & our type the wrapper
        TypeMirror t = v.asType();
        if (t instanceof PrimitiveType) {
            PrimitiveType p = (PrimitiveType)t;
            if (compilationInfo.getTypes().isSameType(
                    compilationInfo.getTypes().boxedClass(p).asType(),
                    classElement.asType())) {
                ok = true;
            }
        } 
        if (!ok) {
            return;
        }
    }
    
    addConstant(v.getSimpleName().toString());
}
 
Example 23
Project: incubator-netbeans   File: MethodModelSupportTest.java   View source code 5 votes vote down vote up
public void testGetTypeName() throws Exception {
    TestUtilities.copyStringToFileObject(testFO,
            "package foo;" +
            "public class TestClass {" +
            "}");
    runUserActionTask(testFO, new Task<CompilationController>() {
        public void run(CompilationController controller) throws IOException {
            controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
            Elements elements = controller.getElements();
            Types types = controller.getTypes();
            
            String typeName = String.class.getName();
            String resolvedTypeName = MethodModelSupport.getTypeName(elements.getTypeElement(typeName).asType());
            assertEquals(typeName, resolvedTypeName);
            
            typeName = InputStream.class.getName();
            resolvedTypeName = MethodModelSupport.getTypeName(elements.getTypeElement(typeName).asType());
            assertEquals(typeName, resolvedTypeName);
            
            resolvedTypeName = MethodModelSupport.getTypeName(types.getPrimitiveType(TypeKind.INT));
            assertEquals("int", resolvedTypeName);

            typeName = String.class.getName();
            resolvedTypeName = MethodModelSupport.getTypeName(types.getArrayType(elements.getTypeElement(typeName).asType()));
            assertEquals("java.lang.String[]", resolvedTypeName);
            
            PrimitiveType primitiveType = types.getPrimitiveType(TypeKind.BYTE);
            ArrayType arrayType = types.getArrayType(primitiveType);
            resolvedTypeName = MethodModelSupport.getTypeName(arrayType);
            assertEquals("byte[]", resolvedTypeName);
        }
    });
}
 
Example 24
Project: ActivityBuilder   File: ParameterWriter.java   View source code 5 votes vote down vote up
/**
 * @return 返回原生类型或者装箱类型的默认值,其他类型返回 null
 */
static String getDefaultValue(TypeMirror typeMirror) {
  switch (typeMirror.getKind()) {
    case BOOLEAN:
      return "false";
    case BYTE:
      return "(byte)0";
    case SHORT:
      return "(short)0";
    case CHAR:
      return "(char)0";
    case INT:
    case LONG:
      return "0";
    case FLOAT:
      return ".0f";
    case DOUBLE:
      return ".0";
    default:
      try {
        PrimitiveType primitiveType = getTypes().unboxedType(typeMirror);
        return getDefaultValue(primitiveType);
      } catch (IllegalArgumentException e) {
        return null;
      }
  }
}
 
Example 25
Project: ActivityBuilder   File: ParameterModel.java   View source code 5 votes vote down vote up
/**
 * 如果是原生类型则返回装箱类型
 */
public TypeMirror getObjectType() {
  if (isPrimitive()) {
    return getTypes().boxedClass((PrimitiveType) getType()).asType();
  } else {
    return type;
  }
}
 
Example 26
Project: ActivityBuilder   File: ParameterModel.java   View source code 5 votes vote down vote up
public boolean isBoxed() {
  try {
    PrimitiveType primitiveType = getTypes().unboxedType(getType());
    if (primitiveType != null) {
      return true;
    }
  } catch (IllegalArgumentException e) {
    // ignore;
  }
  return false;
}
 
Example 27
Project: Router   File: InjectParamProcessor.java   View source code 5 votes vote down vote up
private boolean supportDefaultValue(TypeMirror typeMirror) {
    if (typeMirror instanceof PrimitiveType) {
        return true;
    }
    if (isSubtype(typeMirror, "java.lang.String") || isSubtype(typeMirror, "java.lang.CharSequence")) {
        return true;
    }
    return false;
}
 
Example 28
Project: OpenJSharp   File: TypeMonikerFactory.java   View source code 5 votes vote down vote up
public static TypeMoniker getTypeMoniker(TypeMirror typeMirror) {
    if (typeMirror == null)
        throw new NullPointerException();

    if (typeMirror.getKind().isPrimitive())
        return new PrimitiveTypeMoniker((PrimitiveType) typeMirror);
    else if (typeMirror.getKind().equals(TypeKind.ARRAY))
        return new ArrayTypeMoniker((ArrayType) typeMirror);
    else if (typeMirror.getKind().equals(TypeKind.DECLARED))
        return new DeclaredTypeMoniker((DeclaredType) typeMirror);
    return getTypeMoniker(typeMirror.toString());
}
 
Example 29
Project: qualifier   File: AutoQualifierProcessorProvider.java   View source code 5 votes vote down vote up
@Override public void processAnnotated(Element element, Metaqualifier metaqualifier) {
    if (!metaqualifier.value(autoMethods).isPresent()) {
        metaqualifier.put(autoMethods).value(new ArrayList<>());
    }
    if (!metaqualifier.value(autoAnnotations).isPresent()) {
        metaqualifier.put(autoAnnotations).value(new HashSet<>());
    }
    for (AnnotationMirror aMirror : getAnnotatedAnnotations(element, Qualify.Auto.class)) {
        String packageName = elements().getPackageOf(aMirror.getAnnotationType().asElement()).toString();
        String aUCName = aMirror.getAnnotationType().asElement().getSimpleName().toString();
        String aLCName = UPPER_CAMEL.converterTo(LOWER_CAMEL).convert(aUCName);
        Map<? extends ExecutableElement, ? extends AnnotationValue> values = aMirror.getElementValues();
        for (ExecutableElement e : values.keySet()) {
            metaqualifier.value(autoMethods).ifPresent(am -> {
                String pLCName = e.getSimpleName().toString();
                String pUCName = LOWER_CAMEL.converterTo(UPPER_CAMEL).convert(pLCName);
                TypeMirror pRetType = e.getReturnType();
                if (pRetType.getKind().isPrimitive()) {
                    pRetType = types().boxedClass((PrimitiveType) pRetType).asType();
                }
                boolean isLink = e.getAnnotation(Link.class) != null && isTypeOf(Class.class, pRetType);

                String key = aLCName + "." + pLCName;

                if (!isLink) {
                    metaqualifier.literal(key, annotationFieldAsCodeBlock(getProcessingEnv(), e, values.get(e)));
                } else {
                    String valType = getFlatName((TypeElement) types().asElement((DeclaredType) values.get(e).getValue()));
                    metaqualifier.literal(key, "$T.self", ClassName.bestGuess(getQualifierName(valType)));
                }
            });
            metaqualifier.value(autoAnnotations).ifPresent(aq ->
                    aq.add(ClassName.bestGuess(packageName + "." + aUCName + "Qualifier")));
        }
    }
}
 
Example 30
Project: qualifier   File: StaticQualifierMetamodelProcessor.java   View source code 5 votes vote down vote up
/** The property type. Primitive types are returned as boxed. */
@Override public TypeMirror propertyType() {
    if (name.equals(SELF)) return beanElement().asType();
    TypeMirror typeMirror = type;
    if (typeMirror.getKind().isPrimitive()) {
        typeMirror = types().boxedClass((PrimitiveType) typeMirror).asType();
    }
    return typeMirror;
}
 
Example 31
Project: easybundler   File: Bundler.java   View source code 5 votes vote down vote up
/**
 * Returns {@code true} if the type of an {@link VariableElement} representing an array
 * is a primitive array where the members are a particular {@link TypeKind}.
 */
private boolean matchesPrimitiveArrayClass(VariableElement field, TypeKind kind) {
    PrimitiveType primitiveType = environment.getTypeUtils().getPrimitiveType(kind);
    ArrayType arrayType = environment.getTypeUtils().getArrayType(primitiveType);

    return typesMatch(field.asType(), arrayType, MatchPolicy.EXACT);

}
 
Example 32
Project: android-auto-mapper   File: MoreTypes.java   View source code 5 votes vote down vote up
/**
 * Returns a {@link PrimitiveType} if the {@link TypeMirror} represents a primitive type
 * or throws an {@link IllegalArgumentException}.
 */
public static PrimitiveType asPrimitiveType(TypeMirror maybePrimitiveType) {
    return maybePrimitiveType.accept(new CastingTypeVisitor<PrimitiveType>() {
        @Override
        public PrimitiveType visitPrimitive(PrimitiveType type, String p) {
            return type;
        }
    }, "primitive type");
}
 
Example 33
Project: auto-value-step-builder   File: Generator.java   View source code 5 votes vote down vote up
public Property(Types typeUtils, ExecutableElement element, String name) {
    this.element = element;
    this.name = name;
    this.type = element.getReturnType().toString();
    if (element.getReturnType().getKind().isPrimitive()) {
        PrimitiveType primitiveType = (PrimitiveType) element.getReturnType();
        this.nonPrimitiveType = typeUtils.boxedClass(primitiveType).toString();
        this.primitive = true;
    } else {
        this.nonPrimitiveType = element.getReturnType().toString();
    }
}
 
Example 34
Project: openjdk9   File: TypeMonikerFactory.java   View source code 5 votes vote down vote up
public static TypeMoniker getTypeMoniker(TypeMirror typeMirror) {
    if (typeMirror == null)
        throw new NullPointerException();

    if (typeMirror.getKind().isPrimitive())
        return new PrimitiveTypeMoniker((PrimitiveType) typeMirror);
    else if (typeMirror.getKind().equals(TypeKind.ARRAY))
        return new ArrayTypeMoniker((ArrayType) typeMirror);
    else if (typeMirror.getKind().equals(TypeKind.DECLARED))
        return new DeclaredTypeMoniker((DeclaredType) typeMirror);
    return getTypeMoniker(typeMirror.toString());
}
 
Example 35
Project: alchemy   File: TypeUtils.java   View source code 5 votes vote down vote up
private PrimitiveType unbox(TypeMirror typeMirror) {
    try {
        return mEnv.getTypeUtils().unboxedType(typeMirror);
    } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException("Not a boxed primitive type", e);
    }
}
 
Example 36
Project: neo4j-sproc-compiler   File: TypeMirrorUtils.java   View source code 5 votes vote down vote up
public final Collection<TypeMirror> procedureAllowedTypes()
{
    PrimitiveType bool = primitive( TypeKind.BOOLEAN );
    PrimitiveType longType = primitive( TypeKind.LONG );
    PrimitiveType doubleType = primitive( TypeKind.DOUBLE );
    return asList( bool, boxed( bool ), longType, boxed( longType ), doubleType, boxed( doubleType ),
            typeMirror( String.class ), typeMirror( Number.class ), typeMirror( Object.class ),
            typeMirror( Map.class ), typeMirror( List.class ), typeMirror( Node.class ),
            typeMirror( Relationship.class ), typeMirror( Path.class ) );
}
 
Example 37
Project: Glacier   File: GlacierVisitor.java   View source code 5 votes vote down vote up
private boolean typeIsImmutable(AnnotatedTypeMirror type) {
    TypeMirror underlyingType = type.getUnderlyingType();

    boolean fieldIsImmutable = type.hasAnnotation(Immutable.class);
    if (!fieldIsImmutable) {
        // Check for permitted special cases: primitives and type parameters.
        boolean typeIsPrimitive = underlyingType instanceof PrimitiveType;
        boolean typeIsImmutableClassTypeParameter = false;
        if (underlyingType.getKind() == TypeKind.TYPEVAR) {
            // Type variables can be assumed to be immutable if they are on an immutable class. Otherwise they are unsafe.
            TypeVariable typeVariable = (TypeVariable) underlyingType;
            TypeParameterElement typeVariableElement = (TypeParameterElement) (typeVariable.asElement());
            Element elementEnclosingTypeVariable = typeVariableElement.getGenericElement();
            if (elementEnclosingTypeVariable.getKind() == ElementKind.CLASS || elementEnclosingTypeVariable.getKind() == ElementKind.ENUM) {
                // Check to see if this class is immutable.
                TypeElement classElement = (TypeElement) elementEnclosingTypeVariable;
                AnnotatedTypeMirror classTypeMirror = atypeFactory.getAnnotatedType(classElement);
                if (classTypeMirror.hasAnnotation(Immutable.class)) {
                    typeIsImmutableClassTypeParameter = true;
                }
            }
        }

        if (!typeIsPrimitive && !typeIsImmutableClassTypeParameter) {
            return false;
        }
    }

    if (underlyingType.getKind() == TypeKind.ARRAY) {
        // Arrays must be immutable arrays of immmutable objects.
        AnnotatedArrayType arrayType = (AnnotatedArrayType) type;
        AnnotatedTypeMirror componentType = arrayType.getComponentType();
        return typeIsImmutable(componentType);
    }

    return true;
}
 
Example 38
Project: deltaforce   File: FieldModelBuilderFactory.java   View source code 5 votes vote down vote up
public static TypeMirror autobox(ProcessingEnvironment pe, TypeMirror typeMirror) {

        TypeMirror res;

        if (typeMirror.getKind().isPrimitive()) {
            res = pe.getTypeUtils().boxedClass((PrimitiveType) typeMirror).asType();

        } else if(typeMirror.getKind() == TypeKind.ARRAY){
            res = pe.getTypeUtils().capture(typeMirror);
        }else {
            res = typeMirror;
        }

        return res;
    }
 
Example 39
Project: listing   File: JavaMirrorsTest.java   View source code 5 votes vote down vote up
@Test
void unknownTypeFails() {
  AssertionError e =
      expectThrows(
          AssertionError.class,
          () -> JavaMirrors.of(Tests.proxy(PrimitiveType.class, (p, m, a) -> TypeKind.ERROR)));
  assertTrue(e.toString().contains("Unsupported primitive type"));
  e =
      expectThrows(
          AssertionError.class,
          () -> JavaMirrors.of(Tests.proxy(NoType.class, (p, m, a) -> TypeKind.ERROR)));
  assertTrue(e.toString().contains("Unsupported no type"));
}
 
Example 40
Project: cloudkeeper   File: CloudKeeperTypeReflection.java   View source code 5 votes vote down vote up
@Override
public TypeElement boxedClass(PrimitiveType primitiveType) {
    assert completed;
    Objects.requireNonNull(primitiveType);
    requireValidType(primitiveType);

    return boxedTypes.get(primitiveType.getKind());
}