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 File: AddCast.java From netbeans with Apache License 2.0 | 6 votes |
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 #2
Source File: LLNI.java From jdk8u60 with GNU General Public License v2.0 | 6 votes |
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 #3
Source File: SpecModelUtils.java From litho with Apache License 2.0 | 6 votes |
/** * 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 #4
Source File: Util.java From GoldenGate with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * 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 #5
Source File: NodeIntrinsicVerifier.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
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 #6
Source File: RelationRule.java From alchemy with Apache License 2.0 | 6 votes |
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 #7
Source File: DeptectiveTreeVisitor.java From deptective with Apache License 2.0 | 6 votes |
/** * 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 #8
Source File: MoreTypesTest.java From doma with Apache License 2.0 | 6 votes |
@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 #9
Source File: AutoParcelProcessor.java From auto-parcel with Apache License 2.0 | 6 votes |
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 #10
Source File: EntityMetaFactory.java From doma with Apache License 2.0 | 6 votes |
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 #11
Source File: WebServiceWrapperGenerator.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
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 #12
Source File: PrimitiveTypeAnalyzer.java From Akatsuki with Apache License 2.0 | 6 votes |
@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 #13
Source File: CreateElementUtilities.java From netbeans with Apache License 2.0 | 6 votes |
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 #14
Source File: WebServiceVisitor.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
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 #15
Source File: ContentHeaderAnnotationValidator.java From qpid-broker-j with Apache License 2.0 | 6 votes |
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 #16
Source File: TypeSimplifierTest.java From RetroFacebook with Apache License 2.0 | 6 votes |
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 #17
Source File: Util.java From revapi with Apache License 2.0 | 6 votes |
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 #18
Source File: TreeBackedExecutableElementTest.java From buck with Apache License 2.0 | 5 votes |
@Test public void testVarArgs() throws IOException { compile( Joiner.on('\n') .join("abstract class Foo {", " public abstract void foo(String... strings);", "}")); TypeMirror stringArrayType = types.getArrayType(elements.getTypeElement("java.lang.String").asType()); ExecutableElement method = findMethod("foo", elements.getTypeElement("Foo")); assertTrue(method.isVarArgs()); assertSameType(stringArrayType, findParameter("strings", method).asType()); }
Example #19
Source File: JavaWritableClass.java From HighLite with Apache License 2.0 | 5 votes |
Map<Element, List<Element>> getTypeFieldMap(final Element element) { final Map<Element, List<Element>> ret = new LinkedHashMap<>(); final Stack<Element> typeStack = new Stack<>(); typeStack.push(element); Element currSuperType = element; while (currSuperType != null && !ClassName.get(currSuperType.asType()).equals(TypeName.OBJECT)) { boolean found = false; for (final TypeMirror superType : mTypeUtils.directSupertypes(currSuperType.asType())) { final DeclaredType declared = (DeclaredType) superType; if (declared == null) continue; currSuperType = declared.asElement(); if (ClassName.get(currSuperType.asType()).equals(TypeName.OBJECT) || currSuperType.getAnnotation(SQLiteTable.class) == null) break; if (!currSuperType.getKind().equals(ElementKind.CLASS)) continue; typeStack.push(currSuperType); found = true; break; } if (found) continue; currSuperType = null; } while (!typeStack.empty()) { final Element typeElem = typeStack.pop(); ret.put(typeElem, getFields(typeElem)); } return ret; }
Example #20
Source File: TypeVariableName.java From dagger2-sample with Apache License 2.0 | 5 votes |
public static TypeVariableName fromTypeParameterElement(TypeParameterElement element) { // We filter out bounds of type Object because those would just clutter the generated code. Iterable<? extends TypeName> bounds = FluentIterable.from(element.getBounds()) .filter(new Predicate<TypeMirror>() { @Override public boolean apply(TypeMirror input) { return !MoreTypes.isType(input) || !MoreTypes.isTypeOf(Object.class, input); } }) .transform(TypeNames.FOR_TYPE_MIRROR); return new TypeVariableName(element.getSimpleName(), bounds); }
Example #21
Source File: ExpectedTypeResolver.java From netbeans with Apache License 2.0 | 5 votes |
@Override public List<? extends TypeMirror> visitNewArray(NewArrayTree node, Object p) { if (node.getDimensions() == null) { return null; } if (theExpression == null && node.getDimensions().size() == 1) { initExpression(node.getDimensions().get(0)); } else if (!node.getDimensions().contains(theExpression.getLeaf())) { return null; } return Collections.singletonList(info.getTypes().getPrimitiveType(TypeKind.INT)); }
Example #22
Source File: MoreTypes.java From auto with Apache License 2.0 | 5 votes |
/** * Returns the set of {@linkplain TypeElement types} that are referenced by the given {@link * TypeMirror}. */ public static ImmutableSet<TypeElement> referencedTypes(TypeMirror type) { checkNotNull(type); ImmutableSet.Builder<TypeElement> elements = ImmutableSet.builder(); type.accept(ReferencedTypes.INSTANCE, elements); return elements.build(); }
Example #23
Source File: FunctionalType.java From FreeBuilder with Apache License 2.0 | 5 votes |
public static Optional<FunctionalType> maybeFunctionalType( TypeMirror type, Elements elements, Types types) { return maybeDeclared(type) .flatMap(declaredType -> maybeFunctionalType(declaredType, elements, types)); }
Example #24
Source File: ElementUtilitiesEx.java From netbeans with Apache License 2.0 | 5 votes |
private static String getParamsSignature(List<? extends VariableElement> params, CompilationInfo ci) { StringBuilder ret = new StringBuilder(); Iterator<? extends VariableElement> it = params.iterator(); while (it.hasNext()) { TypeMirror type = it.next().asType(); String realTypeName = getRealTypeName(type, ci); String typeVMSignature = VMUtils.typeToVMSignature(realTypeName); ret.append(typeVMSignature); } return ret.toString(); }
Example #25
Source File: HandleDelegate.java From EasyMPermission with MIT License | 5 votes |
public static String printSig(ExecutableType method, Name name, JavacTypes types) { StringBuilder sb = new StringBuilder(); sb.append(name.toString()).append("("); boolean first = true; for (TypeMirror param : method.getParameterTypes()) { if (!first) sb.append(", "); first = false; sb.append(typeBindingToSignature(param, types)); } return sb.append(")").toString(); }
Example #26
Source File: TypeSimplifierTest.java From RetroFacebook with Apache License 2.0 | 5 votes |
public void testSimplifyAmbiguityFromWithinClass() { TypeMirror otherEntry = typeMirrorOf(TypeSimplifierTest.class.getCanonicalName() + ".Entry"); Set<TypeMirror> types = typeMirrorSet(otherEntry); TypeSimplifier typeSimplifier = new TypeSimplifier(typeUtil, "foo.bar", types, baseDeclaresEntry()); assertEquals(otherEntry.toString(), typeSimplifier.simplify(otherEntry)); }
Example #27
Source File: ProcessorUtils.java From Witch-Android with Apache License 2.0 | 5 votes |
public TypeMirror getDataTypeMirror() { VariableElement element = getDataParameter(); if (element != null) { return typeUtils.boxed(element.asType()); } else { return typeUtils.typeMirror(ClassName.OBJECT); } }
Example #28
Source File: TypeUtil.java From pocketknife with Apache License 2.0 | 5 votes |
private boolean needToCastAggregateType(TypeMirror type) throws InvalidTypeException { if (types.isAssignable(type, charSequenceType)) { return !types.isSameType(type, charSequenceType); } if (types.isAssignable(type, stringType)) { return !types.isSameType(type, stringType); } if (types.isAssignable(type, parcelableType)) { return !types.isSameType(type, parcelableType); } throw new InvalidTypeException(type); }
Example #29
Source File: ScoopsProcesssor.java From Scoops with Apache License 2.0 | 5 votes |
private TypeMirror getInterpolatorTypeMirror(BindTopping annotation){ TypeMirror value = null; try{ annotation.interpolator(); }catch (MirroredTypeException e){ value = e.getTypeMirror(); } return value; }
Example #30
Source File: ScopeTest.java From netbeans with Apache License 2.0 | 5 votes |
public void testCustomScope() throws IOException{ TestUtilities.copyStringToFileObject(srcFO, "foo/CustomScope.java", "package foo; " + "import static java.lang.annotation.ElementType.TYPE; "+ "import static java.lang.annotation.ElementType.METHOD; "+ "import static java.lang.annotation.ElementType.FIELD; "+ "import static java.lang.annotation.RetentionPolicy.RUNTIME; "+ "import java.lang.annotation.*; "+ "import java.lang.annotation.RetentionPolicy; "+ "import javax.enterprise.inject.*; "+ "import javax.enterprise.context.*; "+ "@NormalScope "+ "@Target({TYPE,METHOD,FIELD}) "+ "@Retention(RUNTIME) "+ "@Inherited "+ "public @interface CustomScope {}" ); TestUtilities.copyStringToFileObject(srcFO, "foo/Clazz.java", "package foo; " + "@CustomScope "+ "public class Clazz { " + "}" ); final TestWebBeansModelImpl modelImpl = createModelImpl(true ); MetadataModel<WebBeansModel> testModel = modelImpl.createTestModel(); testModel.runReadAction( new MetadataModelAction<WebBeansModel,Void>(){ @Override public Void run( WebBeansModel model ) throws Exception { TypeMirror mirror = model.resolveType( "foo.Clazz" ); Element clazz = ((DeclaredType)mirror).asElement(); checkScope(model, clazz, "foo.CustomScope"); return null; } }); }