javax.lang.model.type.TypeMirror Java Examples

The following examples show how to use javax.lang.model.type.TypeMirror. 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 Project: alchemy   Author: DanielSerdyukov   File: RelationRule.java    License: Apache License 2.0 6 votes vote down vote up
private void processOneToMany(Element field, Element collectionType, TypeMirror relation) {
    if (!mTypeUtils.isAssignable(collectionType.asType(), List.class)) {
        throw new ElementException("Relation type must be subclass of List<E>", field);
    }
    relation.accept(new SimpleTypeVisitor7<Void, Void>() {
        @Override
        public Void visitDeclared(DeclaredType t, Void unused) {
            final Element element = t.asElement();
            if (element.getAnnotation(Entry.class) == null) {
                throw new ElementException("Related type must be annotated with @Entry", element);
            }
            final Element enclosingElement = field.getEnclosingElement();
            final TableSpec lTable = mCompileGraph.findTableSpec(enclosingElement);
            final TableSpec rTable = mCompileGraph.findTableSpec(element);
            final ClassName className = makeClassName(field);
            final RelationSpec relationSpec = new RelationSpec(
                    field, className, lTable, rTable, true);
            mCompileGraph.putRelationSpec(enclosingElement, relationSpec);
            return super.visitDeclared(t, unused);
        }
    }, null);
}
 
Example #2
Source Project: deptective   Author: moditect   File: DeptectiveTreeVisitor.java    License: 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 #3
Source Project: auto-parcel   Author: aitorvs   File: AutoParcelProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private ImmutableMap<TypeMirror, FieldSpec> getTypeAdapters(ImmutableList<Property> properties) {
    Map<TypeMirror, FieldSpec> typeAdapters = new LinkedHashMap<>();
    NameAllocator nameAllocator = new NameAllocator();
    nameAllocator.newName("CREATOR");
    for (Property property : properties) {
        if (property.typeAdapter != null && !typeAdapters.containsKey(property.typeAdapter)) {
            ClassName typeName = (ClassName) TypeName.get(property.typeAdapter);
            String name = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, typeName.simpleName());
            name = nameAllocator.newName(name, typeName);

            typeAdapters.put(property.typeAdapter, FieldSpec.builder(
                    typeName, NameAllocator.toJavaIdentifier(name), PRIVATE, STATIC, FINAL)
                    .initializer("new $T()", typeName).build());
        }
    }
    return ImmutableMap.copyOf(typeAdapters);
}
 
Example #4
Source Project: revapi   Author: revapi   File: Util.java    License: Apache License 2.0 6 votes vote down vote up
private boolean visitTypeVars(List<? extends TypeMirror> vars, StringBuilderAndState<TypeMirror> state) {
    if (!vars.isEmpty()) {
        Set<Name> names = vars.stream().map(v -> getTypeVariableName.visit(v)).collect(Collectors.toSet());
        state.forwardTypeVarDecls.addAll(names);
        try {
            state.bld.append("<");
            Iterator<? extends TypeMirror> it = vars.iterator();
            it.next().accept(this, state);

            while (it.hasNext()) {
                state.bld.append(", ");
                it.next().accept(this, state);
            }

            state.bld.append(">");
        } finally {
            state.forwardTypeVarDecls.removeAll(names);
        }

        return true;
    }

    return false;
}
 
Example #5
Source Project: Akatsuki   Author: tom91136   File: PrimitiveTypeAnalyzer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public DefaultAnalysis createAnalysis(InvocationContext<TypeMirror> context)
		throws UnknownTypeException {
	// boxed primitives have different names (at least for int)
	CharSequence typeName;
	final TypeMirror refinedMirror = context.field.refinedMirror();
	if (refinedMirror instanceof DeclaredType) {
		// we are boxed
		typeName = this.type == Type.UNBOXED
				? toCapitalCase(types().unboxedType(refinedMirror).getKind().name())
				: ((DeclaredType) refinedMirror).asElement().getSimpleName();
	} else {
		// we are unboxed
		typeName = this.type == Type.BOXED
				? types().boxedClass((PrimitiveType) refinedMirror).getSimpleName()
				: toCapitalCase(refinedMirror.getKind().name());
	}
	String methodName = (suffix != null) ? (typeName.toString() + suffix) : typeName.toString();
	return DefaultAnalysis.of(this, methodName, context);
}
 
Example #6
Source Project: TencentKona-8   Author: Tencent   File: WebServiceVisitor.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected boolean classImplementsSei(TypeElement classElement, TypeElement interfaceElement) {
    for (TypeMirror interfaceType : classElement.getInterfaces()) {
        if (((DeclaredType) interfaceType).asElement().equals(interfaceElement))
            return true;
    }
    List<ExecutableElement> classMethods = getClassMethods(classElement);
    boolean implementsMethod;
    for (ExecutableElement interfaceMethod : ElementFilter.methodsIn(interfaceElement.getEnclosedElements())) {
        implementsMethod = false;
        for (ExecutableElement classMethod : classMethods) {
            if (sameMethod(interfaceMethod, classMethod)) {
                implementsMethod = true;
                classMethods.remove(classMethod);
                break;
            }
        }
        if (!implementsMethod) {
            builder.processError(WebserviceapMessages.WEBSERVICEAP_METHOD_NOT_IMPLEMENTED(interfaceElement.getSimpleName(), classElement.getSimpleName(), interfaceMethod), interfaceMethod);
            return false;
        }
    }
    return true;
}
 
Example #7
Source Project: netbeans   Author: apache   File: AddCast.java    License: Apache License 2.0 6 votes vote down vote up
public List<Fix> run(CompilationInfo info, String diagnosticKey, int offset, TreePath treePath, Data<Void> data) {
    List<Fix> result = new ArrayList<Fix>();
    List<TypeMirror> targetType = new ArrayList<TypeMirror>();
    TreePath[] tmTree = new TreePath[1];
    ExpressionTree[] expression = new ExpressionTree[1];
    Tree[] leaf = new Tree[1];
    
    computeType(info, offset, targetType, tmTree, expression, leaf);
    
    if (!targetType.isEmpty()) {
        TreePath expressionPath = TreePath.getPath(info.getCompilationUnit(), expression[0]); //XXX: performance
        for (TypeMirror type : targetType) {
            if (type.getKind() != TypeKind.NULL) {
                result.add(new AddCastFix(info, expressionPath, tmTree[0], type).toEditorFix());
            }
        }
    }
    
    return result;
}
 
Example #8
Source Project: qpid-broker-j   Author: apache   File: ContentHeaderAnnotationValidator.java    License: Apache License 2.0 6 votes vote down vote up
private void checkMethodReturnsString(TypeElement annotationElement, ExecutableElement methodElement)
{
    final TypeMirror returnType = methodElement.getReturnType();

    if (!isValidType(returnType))
    {
        processingEnv.getMessager()
                .printMessage(Diagnostic.Kind.ERROR,
                        "@"
                                + annotationElement.getSimpleName()
                                + " can only be applied to methods with primitive, boxed primitive, enum, or String type return type but annotated Method "
                                + methodElement.getSimpleName() + " returns "
                                + returnType.toString(),
                        methodElement
                );
    }
}
 
Example #9
Source Project: netbeans   Author: apache   File: CreateElementUtilities.java    License: Apache License 2.0 6 votes vote down vote up
private static List<? extends TypeMirror> computeConditionalExpression(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
    ConditionalExpressionTree cet = (ConditionalExpressionTree) parent.getLeaf();
    
    if (cet.getCondition() == error) {
        types.add(ElementKind.PARAMETER);
        types.add(ElementKind.LOCAL_VARIABLE);
        types.add(ElementKind.FIELD);
        
        return Collections.singletonList(info.getTypes().getPrimitiveType(TypeKind.BOOLEAN));
    }
    
    if (cet.getTrueExpression() == error || cet.getFalseExpression() == error) {
        types.add(ElementKind.PARAMETER);
        types.add(ElementKind.LOCAL_VARIABLE);
        types.add(ElementKind.FIELD);
        
        return resolveType(types, info, parent.getParentPath(), cet, offset, null, null);
    }
    
    return null;
}
 
Example #10
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: WebServiceWrapperGenerator.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void writeMember(JDefinedClass cls, TypeMirror paramType,
                         String paramName) {

    if (cls == null)
        return;

    String accessorName =BindingHelper.mangleNameToPropertyName(paramName);
    String getterPrefix = paramType.toString().equals("boolean")? "is" : "get";
    JType propType = getType(paramType);
    JMethod m = cls.method(JMod.PUBLIC, propType, getterPrefix+ accessorName);
    JDocComment methodDoc = m.javadoc();
    JCommentPart ret = methodDoc.addReturn();
    ret.add("returns "+propType.name());
    JBlock body = m.body();
    body._return( JExpr._this().ref(paramName) );

    m = cls.method(JMod.PUBLIC, cm.VOID, "set"+accessorName);
    JVar param = m.param(propType, paramName);
    methodDoc = m.javadoc();
    JCommentPart part = methodDoc.addParam(paramName);
    part.add("the value for the "+ paramName+" property");
    body = m.body();
    body.assign( JExpr._this().ref(paramName), param );
}
 
Example #11
Source Project: doma   Author: domaframework   File: EntityMetaFactory.java    License: Apache License 2.0 6 votes vote down vote up
void validateNonGenericEntityListener(
    TypeElement classElement, EntityMeta entityMeta, TypeMirror listenerType) {
  EntityAnnot entityAnnot = entityMeta.getEntityAnnot();
  TypeMirror argumentType = getListenerArgumentType(listenerType);
  if (argumentType == null) {
    throw new AptException(
        Message.DOMA4202,
        classElement,
        entityAnnot.getAnnotationMirror(),
        entityAnnot.getListener(),
        new Object[] {});
  }
  if (!ctx.getMoreTypes().isAssignableWithErasure(classElement.asType(), argumentType)) {
    throw new AptException(
        Message.DOMA4038,
        classElement,
        entityAnnot.getAnnotationMirror(),
        entityAnnot.getListener(),
        new Object[] {listenerType, argumentType, classElement.getQualifiedName()});
  }
}
 
Example #12
Source Project: RetroFacebook   Author: yongjhih   File: TypeSimplifierTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testImportsForArrayTypes() {
  TypeElement list = typeElementOf("java.util.List");
  TypeElement set = typeElementOf("java.util.Set");
  Set<TypeMirror> types = typeMirrorSet(
      typeUtil.getArrayType(typeUtil.getPrimitiveType(TypeKind.INT)),
      typeUtil.getArrayType(typeMirrorOf("java.util.regex.Pattern")),
      typeUtil.getArrayType(          // Set<Matcher[]>[]
          typeUtil.getDeclaredType(set,
              typeUtil.getArrayType(typeMirrorOf("java.util.regex.Matcher")))),
      typeUtil.getDeclaredType(list,  // List<Timer[]>
          typeUtil.getArrayType(typeMirrorOf("java.util.Timer"))));
  // Timer is referenced twice but should obviously only be imported once.
  List<String> expectedImports = ImmutableList.of(
      "java.util.List",
      "java.util.Set",
      "java.util.Timer",
      "java.util.regex.Matcher",
      "java.util.regex.Pattern"
  );
  TypeSimplifier typeSimplifier =
      new TypeSimplifier(typeUtil, "foo.bar", types, baseWithoutContainedTypes());
  assertEquals(expectedImports, ImmutableList.copyOf(typeSimplifier.typesToImport()));
}
 
Example #13
Source Project: GoldenGate   Author: Flipboard   File: Util.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Returns the {@link TypeMirror} for a given {@link Class}.
 *
 * Adapter from https://github.com/typetools/checker-framework/
 */
public static TypeMirror typeFromClass(Types types, Elements elements, Class<?> clazz) {
    if (clazz == void.class) {
        return types.getNoType(TypeKind.VOID);
    } else if (clazz.isPrimitive()) {
        String primitiveName = clazz.getName().toUpperCase();
        TypeKind primitiveKind = TypeKind.valueOf(primitiveName);
        return types.getPrimitiveType(primitiveKind);
    } else if (clazz.isArray()) {
        TypeMirror componentType = typeFromClass(types, elements, clazz.getComponentType());
        return types.getArrayType(componentType);
    } else {
        TypeElement element = elements.getTypeElement(clazz.getCanonicalName());
        if (element == null) {
            throw new IllegalArgumentException("Unrecognized class: " + clazz);
        }
        return element.asType();
    }
}
 
Example #14
Source Project: jdk8u60   Author: chenghanpeng   File: LLNI.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected final String jniMethodName(ExecutableElement method, String cname,
                                     boolean longName)
            throws TypeSignature.SignatureException {
    String res = "Java_" + cname + "_" + method.getSimpleName();

    if (longName) {
        TypeMirror mType =  types.erasure(method.getReturnType());
        List<? extends VariableElement> params = method.getParameters();
        List<TypeMirror> argTypes = new ArrayList<TypeMirror>();
        for (VariableElement param: params) {
            argTypes.add(types.erasure(param.asType()));
        }

        res = res + "__";
        for (TypeMirror t: argTypes) {
            String tname = t.toString();
            TypeSignature newTypeSig = new TypeSignature(elems);
            String sig = newTypeSig.getTypeSignature(tname);
            res = res + nameToIdentifier(sig);
        }
    }
    return res;
}
 
Example #15
Source Project: litho   Author: facebook   File: SpecModelUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * There are a few cases of classes with typeArgs (e.g. {@literal MyClass<SomeClass, ..>}) where
 *
 * <p>TypeName.get() throws an error like: "com.sun.tools.javac.code.Symbol$CompletionFailure:
 * class file for SomeClass not found". Therefore we manually get the qualified name and create
 * the TypeName from the path String.
 */
private static TypeName safelyGetTypeName(TypeMirror t) {
  TypeName typeName;
  try {
    typeName = TypeName.get(t);
  } catch (Exception e) {
    final String qualifiedName;
    if (t instanceof DeclaredType) {
      qualifiedName =
          ((TypeElement) ((DeclaredType) t).asElement()).getQualifiedName().toString();
    } else {
      String tmp = t.toString();
      qualifiedName = tmp.substring(0, tmp.indexOf('<'));
    }

    typeName = ClassName.bestGuess(qualifiedName);
  }

  return typeName;
}
 
Example #16
Source Project: doma   Author: domaframework   File: MoreTypesTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void getTypeName() {
  addProcessor(
      new TestProcessor() {
        @Override
        protected void run() {
          TypeMirror intType = ctx.getMoreTypes().getPrimitiveType(TypeKind.INT);
          assertEquals("int", ctx.getMoreTypes().getTypeName(intType));
          TypeMirror listType = ctx.getMoreElements().getTypeElement(List.class).asType();
          assertEquals("java.util.List<E>", ctx.getMoreTypes().getTypeName(listType));
        }
      },
      new TestProcessor() {
        @Override
        protected void run() {
          TypeElement typeElement = ctx.getMoreElements().getTypeElement(NumberList.class);
          TypeParameterElement typeParameterElement =
              typeElement.getTypeParameters().iterator().next();
          assertEquals("E", ctx.getMoreTypes().getTypeName(typeParameterElement.asType()));
        }
      });
}
 
Example #17
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: NodeIntrinsicVerifier.java    License: GNU General Public License v2.0 6 votes vote down vote up
private ExecutableElement findConstructor(TypeElement nodeClass, TypeMirror[] signature, ExecutableElement intrinsicMethod, AnnotationMirror intrinsicAnnotation) {
    List<ExecutableElement> constructors = ElementFilter.constructorsIn(nodeClass.getEnclosedElements());
    List<String> failureReasons = new ArrayList<>();

    for (ExecutableElement constructor : constructors) {
        String failureReason = matchSignature(0, constructor, signature);
        if (failureReason == null) {
            // found
            return constructor;
        }

        failureReasons.add(failureReason);
    }

    // not found
    if (failureReasons.isEmpty()) {
        env.getMessager().printMessage(Kind.ERROR, "Could not find matching constructor for node intrinsic.", intrinsicMethod, intrinsicAnnotation);
    } else {
        for (String reason : failureReasons) {
            env.getMessager().printMessage(Kind.ERROR, reason, intrinsicMethod, intrinsicAnnotation);
        }
    }

    return null;
}
 
Example #18
Source Project: netbeans   Author: apache   File: ElementOverlay.java    License: Apache License 2.0 5 votes vote down vote up
private void addElement(ASTService ast, Elements elements, TypeMirror tm, List<Element> result) {
    if (tm == null || tm.getKind() != TypeKind.DECLARED) {
        return;
    }
    
    String fqn = ((TypeElement) ((DeclaredType) tm).asElement()).getQualifiedName().toString();
    Element resolved = resolve(ast, elements, fqn, moduleOf(elements, ((DeclaredType)tm).asElement()));
    
    if (resolved != null) {
        result.add(resolved);
    } else {
        Logger.getLogger(ElementOverlay.class.getName()).log(Level.FINE, "cannot resolve {0}", fqn);
    }
}
 
Example #19
Source Project: DataLoader   Author: JeremyLiao   File: DataLoaderProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isFromInterface(TypeElement typeElement, String interfaceName) {
    for (TypeMirror anInterface : typeElement.getInterfaces()) {
        if (anInterface.toString().equals(interfaceName)) {
            return true;
        } else {
            boolean isInterface = isFromInterface((TypeElement) asElement(anInterface), interfaceName);
            if (isInterface) {
                return true;
            }
        }
    }
    return false;
}
 
Example #20
Source Project: j2cl   Author: google   File: MoreApt.java    License: Apache License 2.0 5 votes vote down vote up
public static ImmutableList<TypeElement> getHierarchyImpl(
    TypeElement typeElement, boolean includeInterfaces) {
  ImmutableList.Builder<TypeElement> classHierarchyBuilder = new ImmutableList.Builder<>();
  for (TypeElement t = typeElement; t != null; t = asTypeElement(t.getSuperclass())) {
    classHierarchyBuilder.add(t);
    if (includeInterfaces) {
      for (TypeMirror i : t.getInterfaces()) {
        classHierarchyBuilder.addAll(getHierarchyImpl(asTypeElement(i), includeInterfaces));
      }
    }
  }
  return classHierarchyBuilder.build();
}
 
Example #21
Source Project: jlibs   Author: santhosh-tekuri   File: ModelUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static String signature(ExecutableElement method, boolean useParamNames){
    StringBuilder buff = new StringBuilder();

    Set<Modifier> modifiers = method.getModifiers();
    Modifier modifier = getModifier(modifiers, Modifier.PUBLIC, Modifier.PROTECTED, Modifier.PRIVATE);
    if(modifier!=null)
        buff.append(modifier).append(' ');

    buff.append(toString(method.getReturnType(), false));
    buff.append(' ');
    buff.append(method.getSimpleName());
    buff.append('(');
    int i = 0;
    for(VariableElement param : method.getParameters()){
        if(i>0)
            buff.append(", ");
        buff.append(toString(param.asType(), false));
        if(useParamNames)
            buff.append(' ').append(param.getSimpleName());
        i++;
    }
    buff.append(')');

    List<? extends TypeMirror> throwTypes = method.getThrownTypes();
    if(throwTypes.size()>0){
        buff.append(" throws ");
        i = 0;
        for(TypeMirror throwType: throwTypes){
            if(i>0)
                buff.append(", ");
            buff.append(throwType);
            i++;
        }
    }

    return buff.toString();
}
 
Example #22
Source Project: dsl-json   Author: ngs-doo   File: Analysis.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private boolean isCompatibileCollection(TypeMirror left, TypeMirror rawCollection) {
	final String leftStr = left.toString();
	final String rightStr = rawCollection.toString();
	if (leftStr.equals(rightStr)) return true;
	if (left.getKind() != rawCollection.getKind()) return false;
	TypeMirror leftRaw = types.erasure(left);
	return types.isAssignable(rawCollection, leftRaw);
}
 
Example #23
Source Project: openjdk-8   Author: bpupadhyaya   File: AnnotationProxyMaker.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void visitArray(Attribute.Array a) {
    Name elemName = ((ArrayType) a.type).elemtype.tsym.getQualifiedName();

    if (elemName.equals(elemName.table.names.java_lang_Class)) {   // Class[]
        // Construct a proxy for a MirroredTypesException
        ListBuffer<TypeMirror> elems = new ListBuffer<TypeMirror>();
        for (Attribute value : a.values) {
            Type elem = ((Attribute.Class) value).classType;
            elems.append(elem);
        }
        value = new MirroredTypesExceptionProxy(elems.toList());

    } else {
        int len = a.values.length;
        Class<?> returnClassSaved = returnClass;
        returnClass = returnClass.getComponentType();
        try {
            Object res = Array.newInstance(returnClass, len);
            for (int i = 0; i < len; i++) {
                a.values[i].accept(this);
                if (value == null || value instanceof ExceptionProxy) {
                    return;
                }
                try {
                    Array.set(res, i, value);
                } catch (IllegalArgumentException e) {
                    value = null;       // indicates a type mismatch
                    return;
                }
            }
            value = res;
        } finally {
            returnClass = returnClassSaved;
        }
    }
}
 
Example #24
Source Project: revapi   Author: revapi   File: Util.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Void visitWildcard(WildcardType t, StringBuilderAndState<TypeMirror> state) {
    TypeMirror extendsBound = IgnoreCompletionFailures.in(t::getExtendsBound);

    if (state.visitingMethod) {
        if (extendsBound != null) {
            extendsBound.accept(this, state);
        } else {
            //super bound or unbound wildcard
            state.bld.append("java.lang.Object");
        }

        return null;
    }

    TypeMirror superBound = IgnoreCompletionFailures.in(t::getSuperBound);

    if (superBound != null) {
        superBound.accept(this, state);
        state.bld.append("-");
    }

    if (extendsBound != null) {
        extendsBound.accept(this, state);
        state.bld.append("+");
    }

    return null;
}
 
Example #25
Source Project: netbeans   Author: apache   File: ConvertToLambdaPreconditionChecker.java    License: Apache License 2.0 5 votes vote down vote up
private List<TypeMirror> getTypesFromElements(List<? extends VariableElement> elements) {
    List<TypeMirror> elementTypes = new ArrayList<TypeMirror>();
    for (Element e : elements) {
        elementTypes.add(e.asType());
    }
    return elementTypes;
}
 
Example #26
Source Project: kripton   Author: xcesco   File: TypeUtility.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Convert.
 *
 * @param input
 *            the input
 * @return the list
 */
private static List<TypeName> convert(List<? extends TypeMirror> input) {
	List<TypeName> result = new ArrayList<TypeName>();

	for (TypeMirror item : input) {
		result.add(TypeUtility.typeName(item));
	}

	return result;
}
 
Example #27
Source Project: gama   Author: gama-platform   File: VarsProcessor.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void createElement(final StringBuilder sb, final ProcessorContext context, final Element e,
		final vars vars) {
	final TypeMirror typeClass = e.asType();
	final boolean isField = !context.getTypeUtils().isAssignable(typeClass, context.getISkill())
			&& !context.getTypeUtils().isAssignable(typeClass, context.getIAgent());

	for (final variable node : vars.value()) {
		verifyDoc(context, e, "attribute " + node.name(), node);
		final String clazz = rawNameOf(context, e.asType());
		final String clazzObject = toClassObject(clazz);

		sb.append(in).append(isField ? "_field(" : "_var(").append(clazzObject);
		// if (!isField) {
		// sb.append(",").append(toJavaString(escapeDoubleQuotes(d)));
		// }
		sb.append(",");
		if (isField) {
			sb.append("_proto(").append(toJavaString(node.name())).append(',');
			writeHelpers(sb, context, node, clazz, e, isField, true);
			sb.append(',').append(node.type()).append(',').append(clazzObject).append(',').append(node.type())
					.append(",").append(node.of()).append(',').append(node.index()).append(')');
		} else {
			sb.append("desc(").append(node.type()).append(',');
			writeFacets(sb, node);
			sb.append("),");
			writeHelpers(sb, context, node, clazz, e, isField, false);
		}
		sb.append(");");
	}

}
 
Example #28
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: LoadProc.java    License: GNU General Public License v2.0 5 votes vote down vote up
String desc(TypeMirror tm) {
    switch (tm.getKind()) {
        case BOOLEAN:
            return "Z";
        case BYTE:
            return "B";
        case SHORT:
            return "S";
        case CHAR:
            return "C";
        case INT:
            return "I";
        case LONG:
            return "J";
        case FLOAT:
            return "F";
        case DOUBLE:
            return "D";
        case VOID:
            return "V";
        case DECLARED:
            String s =
                ((TypeElement)((DeclaredType)tm).asElement()).getQualifiedName().toString();
            s = s.replace('.', '/');
            return "L" + s + ";";
        case ARRAY:
            return "[" + desc(((ArrayType)tm).getComponentType());
        default:
            return tm.getKind().toString();
    }
}
 
Example #29
Source Project: SimpleWeibo   Author: 8tory   File: TypeSimplifierTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testSimplifyComplicatedTypes() {
  TypeElement list = typeElementOf("java.util.List");
  TypeElement map = typeElementOf("java.util.Map");
  TypeMirror string = typeMirrorOf("java.lang.String");
  TypeMirror integer = typeMirrorOf("java.lang.Integer");
  TypeMirror pattern = typeMirrorOf("java.util.regex.Pattern");
  TypeMirror timer = typeMirrorOf("java.util.Timer");
  TypeMirror bigInteger = typeMirrorOf("java.math.BigInteger");
  Set<TypeMirror> types = typeMirrorSet(
      typeUtil.getPrimitiveType(TypeKind.INT),
      typeUtil.getArrayType(typeUtil.getPrimitiveType(TypeKind.BYTE)),
      pattern,
      typeUtil.getArrayType(pattern),
      typeUtil.getArrayType(typeUtil.getArrayType(pattern)),
      typeUtil.getDeclaredType(list, typeUtil.getWildcardType(null, null)),
      typeUtil.getDeclaredType(list, timer),
      typeUtil.getDeclaredType(map, string, integer),
      typeUtil.getDeclaredType(map,
          typeUtil.getWildcardType(timer, null), typeUtil.getWildcardType(null, bigInteger)));
  Set<String> expectedSimplifications = ImmutableSet.of(
      "int",
      "byte[]",
      "Pattern",
      "Pattern[]",
      "Pattern[][]",
      "List<?>",
      "List<Timer>",
      "Map<String, Integer>",
      "Map<? extends Timer, ? super BigInteger>"
  );
  TypeSimplifier typeSimplifier =
      new TypeSimplifier(typeUtil, "foo.bar", types, baseWithoutContainedTypes());
  Set<String> actualSimplifications = new HashSet<String>();
  for (TypeMirror type : types) {
    actualSimplifications.add(typeSimplifier.simplify(type));
  }
  assertEquals(expectedSimplifications, actualSimplifications);
}
 
Example #30
Source Project: netbeans   Author: apache   File: AnnotationPostContruct.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean throwsCheckedException(CompilationInfo info, List<? extends TypeMirror> thrownTypes) {
    for (TypeMirror typeMirror : thrownTypes) {
        boolean runtimeException = false;
        TypeElement element = info.getElements().getTypeElement(typeMirror.toString());
        if (element != null) { //NOI18N
            if (JavaUtils.isTypeOf(info, element, "java.lang.RuntimeException")) { //NOI18N
                runtimeException = true;
            }
        }
        if (!runtimeException) {
            return true;
        }
    }
    return false;
}