javax.lang.model.type.PrimitiveType Java Examples

The following examples show how to use javax.lang.model.type.PrimitiveType. 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: RpcProxyGenerator.java    From fastjgame with Apache License 2.0 6 votes vote down vote up
private TypeMirror getNonPrimitiveReturnType(ExecutableElement method) {
    if (method.getReturnType().getKind() == TypeKind.VOID) {
        return processor.wildcardType;
    }

    if (method.getReturnType().getKind().isPrimitive()) {
        // 可能是基础类型
        return typeUtils.boxedClass((PrimitiveType) method.getReturnType()).asType();
    }

    if (processor.isFuture(method.getReturnType())) {
        // future类型,捕获泛型参数
        return findFutureTypeArgument(method);
    } else {
        return method.getReturnType();
    }
}
 
Example #2
Source File: ConfiguredObjectFactoryGenerator.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
private String getBoxedReturnTypeAsString(final ExecutableElement methodElement)
{
    TypeMirror returnType = methodElement.getReturnType();
    String returnTypeName;
    if (returnType.getKind().isPrimitive())
    {
        TypeElement returnTypeElement =
                processingEnv.getTypeUtils().boxedClass((PrimitiveType) returnType);
        returnTypeName = returnTypeElement.asType().toString();
    }
    else if (returnType.getKind() == TypeKind.VOID)
    {
        returnTypeName = "Void";
    }
    else
    {
        returnTypeName = methodElement.getReturnType().toString();
    }
    return returnTypeName;
}
 
Example #3
Source File: PrimitiveTypeAnalyzer.java    From Akatsuki with 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 #4
Source File: SourceModeler.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private Collection<TypeMirror> getBoxedPrimitives( 
        CompilationController controller)
{
    TypeKind[] values = TypeKind.values();
    Collection<TypeMirror> result = new ArrayList<TypeMirror>( values.length);
    for (TypeKind typeKind : values) {
        if ( typeKind.isPrimitive() ){
            PrimitiveType primitiveType = 
                controller.getTypes().getPrimitiveType(typeKind);
            TypeElement boxedClass = controller.getTypes().
                boxedClass(primitiveType);
            result.add( boxedClass.asType() );
        }
    }
    return result;
}
 
Example #5
Source File: ExpectedTypeResolver.java    From netbeans with Apache License 2.0 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 #6
Source File: ReplaceBufferByString.java    From netbeans with Apache License 2.0 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 #7
Source File: PreconditionsChecker.java    From netbeans with Apache License 2.0 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 #8
Source File: Analyser.java    From FreeBuilder with Apache License 2.0 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 (method.getEnclosingElement().equals(valueType)) {
      propertyBuilder.setInEqualsAndHashCode(method.getAnnotation(IgnoredByEquals.class) == null);
      propertyBuilder.setInToString(method.getAnnotation(NotInToString.class) == null);
  }
  if (propertyType.getKind().isPrimitive()) {
    PrimitiveType unboxedType = types.getPrimitiveType(propertyType.getKind());
    TypeMirror boxedType = types.erasure(types.boxedClass(unboxedType).asType());
    propertyBuilder.setBoxedType(boxedType);
  }
}
 
Example #9
Source File: FunctionalType.java    From FreeBuilder with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a unary operator that will accept {@code type}, without autoboxing if possible.
 */
public static FunctionalType unboxedUnaryOperator(TypeMirror type, Types types) {
  switch (type.getKind()) {
    case INT:
    case LONG:
    case DOUBLE:
      return primitiveUnaryOperator((PrimitiveType) type);

    case BOOLEAN:
    case BYTE:
    case CHAR:
    case SHORT:
    case FLOAT:
      return unaryOperator(types.boxedClass((PrimitiveType) type).asType());

    default:
      return unaryOperator(type);
  }
}
 
Example #10
Source File: CtTypes.java    From doma with Apache License 2.0 6 votes vote down vote up
@Override
public Class<?> visitPrimitive(PrimitiveType t, Void p) {
  switch (t.getKind()) {
    case BOOLEAN:
      return PrimitiveBooleanWrapper.class;
    case BYTE:
      return PrimitiveByteWrapper.class;
    case SHORT:
      return PrimitiveShortWrapper.class;
    case INT:
      return PrimitiveIntWrapper.class;
    case LONG:
      return PrimitiveLongWrapper.class;
    case FLOAT:
      return PrimitiveFloatWrapper.class;
    case DOUBLE:
      return PrimitiveDoubleWrapper.class;
    case CHAR:
      return null;
    default:
      return assertUnreachable();
  }
}
 
Example #11
Source File: TypedMethodAnalyzer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean hasUnrestrictedOverridenType( TypeMirror elementType,
        List<TypeMirror> restrictedTypes, CompilationInfo compInfo,
        ExecutableElement overriddenMethod, TypeElement superClass )
{
    TypeMirror methodType = compInfo.getTypes().asMemberOf(
            (DeclaredType)superClass.asType(), overriddenMethod);
    TypeMirror returnOverriden = ((ExecutableType)methodType).getReturnType();
    if ( elementType.getKind() == TypeKind.ARRAY ){
        for( TypeMirror mirror : restrictedTypes ){
            if ( compInfo.getTypes().isSameType( mirror, returnOverriden)){
                return true;
            }
        }
        return false;
    }
    else if ( returnOverriden.getKind().isPrimitive() ) {
        TypeElement boxed = compInfo.getTypes().boxedClass(
                (PrimitiveType)returnOverriden);
        return hasUnrestrictedType(boxed, restrictedTypes, compInfo);
    }
    else if ( returnOverriden instanceof DeclaredType ){
        Element returnElement = compInfo.getTypes().asElement( returnOverriden);
        if ( returnElement instanceof TypeElement ){
            return hasUnrestrictedType((TypeElement)returnElement, 
                    restrictedTypes, compInfo);
        }
    }
    return true;
}
 
Example #12
Source File: Marshallers.java    From bazel with Apache License 2.0 5 votes vote down vote up
private SerializationCodeGenerator getMatchingCodeGenerator(TypeMirror type)
    throws SerializationProcessingFailedException {
  if (type.getKind() == TypeKind.ARRAY) {
    return arrayCodeGenerator;
  }

  if (type instanceof PrimitiveType) {
    PrimitiveType primitiveType = (PrimitiveType) type;
    return primitiveGenerators.stream()
        .filter(generator -> generator.matches((PrimitiveType) type))
        .findFirst()
        .orElseThrow(
            () ->
                new SerializationProcessingFailedException(
                    null, "No generator for: %s", primitiveType));
  }

  // We're dealing with a generic.
  if (isVariableOrWildcardType(type)) {
    return contextMarshaller;
  }

  // TODO(cpeyser): Refactor primitive handling from AutoCodecProcessor.java
  if (!(type instanceof DeclaredType)) {
    throw new IllegalArgumentException(
        "Can only serialize primitive, array or declared fields, found " + type);
  }
  DeclaredType declaredType = (DeclaredType) type;

  return marshallers
      .stream()
      .filter(marshaller -> marshaller.matches(declaredType))
      .findFirst()
      .orElseThrow(
          () ->
              new IllegalArgumentException(
                  "No marshaller for: "
                      + ((TypeElement) declaredType.asElement()).getQualifiedName()));
}
 
Example #13
Source File: BeanModelBuilder.java    From netbeans with Apache License 2.0 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 #14
Source File: TypeUtils.java    From Witch-Android with Apache License 2.0 5 votes vote down vote up
TypeMirror boxed(TypeMirror type) {

        // Box if primitive
        if(type.getKind() != null && type.getKind().isPrimitive()) {
            return types.boxedClass((PrimitiveType) type).asType();
        }
        return type;
    }
 
Example #15
Source File: TypeMonikerFactory.java    From openjdk-8-source with GNU General Public License v2.0 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 #16
Source File: TypeMonikerFactory.java    From TencentKona-8 with GNU General Public License v2.0 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 #17
Source File: TypeUtils.java    From alchemy with Apache License 2.0 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 #18
Source File: TurbineTypes.java    From turbine with Apache License 2.0 5 votes vote down vote up
@Override
public PrimitiveType unboxedType(TypeMirror typeMirror) {
  Type type = asTurbineType(typeMirror);
  if (type.tyKind() != TyKind.CLASS_TY) {
    throw new IllegalArgumentException(type.toString());
  }
  TurbineConstantTypeKind unboxed = unboxedType((ClassTy) type);
  if (unboxed == null) {
    throw new IllegalArgumentException(type.toString());
  }
  return (PrimitiveType) factory.asTypeMirror(PrimTy.create(unboxed, ImmutableList.of()));
}
 
Example #19
Source File: TurbineTypesFactoryTest.java    From turbine with Apache License 2.0 5 votes vote down vote up
@Test
public void primitiveTypes() {
  for (TypeKind kind : TypeKind.values()) {
    if (kind.isPrimitive()) {
      PrimitiveType type = turbineTypes.getPrimitiveType(kind);
      assertThat(type.getKind()).isEqualTo(kind);
    } else {
      try {
        turbineTypes.getPrimitiveType(kind);
        fail();
      } catch (IllegalArgumentException expected) {
      }
    }
  }
}
 
Example #20
Source File: TurbineTypesUnaryTest.java    From turbine with Apache License 2.0 5 votes vote down vote up
@Test
public void boxedClass() {
  assume().that(javacA).isInstanceOf(PrimitiveType.class);
  assume().that(turbineA).isInstanceOf(PrimitiveType.class);

  String expected = javacTypes.boxedClass((PrimitiveType) javacA).toString();
  String actual = turbineTypes.boxedClass((PrimitiveType) turbineA).toString();
  assertWithMessage("boxedClass(`%s`) = boxedClass(`%s`)", javacA, turbineA)
      .that(actual)
      .isEqualTo(expected);
}
 
Example #21
Source File: TypeMonikerFactory.java    From openjdk-8 with GNU General Public License v2.0 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 #22
Source File: MoreTypes.java    From auto-parcel with Apache License 2.0 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 #23
Source File: Environment.java    From sqlitemagic with Apache License 2.0 5 votes vote down vote up
private Dual<TypeElement, Boolean> getTypeElement(final TypeMirror elementType) {
  TypeElement typeElement = elementUtils.getTypeElement(elementType.toString());
  boolean isPrimitive = false;
  if (typeElement == null) {
    try {
      typeElement = typeUtils.boxedClass((PrimitiveType) elementType);
      isPrimitive = true;
    } catch (Exception e) {
      return null;
    }
  }
  return Dual.create(typeElement, isPrimitive);
}
 
Example #24
Source File: ColumnElement.java    From sqlitemagic with Apache License 2.0 5 votes vote down vote up
public static TypeName findEquivalentType(ExtendedTypeElement serializedType,
                                          Environment environment) {
  final Types typeUtils = environment.getTypeUtils();
  TypeMirror typeMirror = serializedType.getTypeMirror();
  if (typeMirror instanceof PrimitiveType) {
    typeMirror = typeUtils.boxedClass((PrimitiveType) typeMirror).asType();
  }
  if (typeUtils.isSubtype(typeMirror, NUMBER_TYPE)) {
    return NUMBER;
  }
  if (typeUtils.isSubtype(typeMirror, CHAR_SEQUENCE_TYPE)) {
    return CHAR_SEQUENCE;
  }
  return typeNameForGenerics(serializedType);
}
 
Example #25
Source File: MissingTypeAwareDelegatingTypes.java    From revapi with Apache License 2.0 5 votes vote down vote up
@Override
public PrimitiveType unboxedType(TypeMirror t) {
    if (isMissing(t)) {
        throw new IllegalArgumentException("Type " + t + " does not have an unboxing conversion.");
    }
    return IgnoreCompletionFailures.in(types::unboxedType, t);
}
 
Example #26
Source File: TreeBackedTypesTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsSameTypePrimitiveType() throws IOException {
  initCompiler();

  for (TypeKind typeKind : TypeKind.values()) {
    if (typeKind.isPrimitive()) {
      PrimitiveType primitiveType = types.getPrimitiveType(typeKind);
      PrimitiveType primitiveType2 = types.getPrimitiveType(typeKind);

      assertSameType(primitiveType, primitiveType2);
    }
  }
}
 
Example #27
Source File: CtTypes.java    From doma with Apache License 2.0 5 votes vote down vote up
private OptionalLongCtType newOptionalLongCtType(TypeMirror type) {
  if (!ctx.getMoreTypes().isSameTypeWithErasure(type, OptionalLong.class)) {
    return null;
  }
  PrimitiveType primitiveType = ctx.getMoreTypes().getPrimitiveType(TypeKind.LONG);
  BasicCtType elementCtType = newBasicCtType(primitiveType);
  return new OptionalLongCtType(ctx, type, elementCtType);
}
 
Example #28
Source File: Rewriter.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private TypeKind getPrimitiveKind(TypeMirror t) {
  if (t == null) {
    return null;
  }
  if (t.getKind().isPrimitive()) {
    return t.getKind();
  }
  PrimitiveType p = typeUtil.unboxedType(t);
  return p != null ? p.getKind() : null;
}
 
Example #29
Source File: FunctionalType.java    From FreeBuilder with Apache License 2.0 5 votes vote down vote up
/**
 * Returns one of {@link IntUnaryOperator}, {@link LongUnaryOperator} or
 * {@link DoubleUnaryOperator}, depending on {@code type}.
 *
 * @throws IllegalArgumentException if {@code type} is not one of int, long or double
 */
public static FunctionalType primitiveUnaryOperator(PrimitiveType type) {
  switch (type.getKind()) {
    case INT:
      return new FunctionalType(
          Type.from(IntUnaryOperator.class),
          "applyAsInt",
          ImmutableList.of(type),
          type);

    case LONG:
      return new FunctionalType(
          Type.from(LongUnaryOperator.class),
          "applyAsLong",
          ImmutableList.of(type),
          type);

    case DOUBLE:
      return new FunctionalType(
          Type.from(DoubleUnaryOperator.class),
          "applyAsDouble",
          ImmutableList.of(type),
          type);

    default:
      throw new IllegalArgumentException("No primitive unary operator exists for " + type);
  }
}
 
Example #30
Source File: TypesImpl.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public TypeElement boxedClass(PrimitiveType p) {
    PrimitiveTypeImpl primitiveTypeImpl = (PrimitiveTypeImpl) p;
    BaseTypeBinding baseTypeBinding = (BaseTypeBinding)primitiveTypeImpl._binding;
    TypeBinding boxed = _env.getLookupEnvironment().computeBoxingType(baseTypeBinding);
    return (TypeElement) _env.getFactory().newElement(boxed);
}