javax.lang.model.util.Types Java Examples
The following examples show how to use
javax.lang.model.util.Types.
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: AttributeMember.java From requery with Apache License 2.0 | 6 votes |
private ElementValidator validateCollectionType(ProcessingEnvironment processingEnvironment) { Types types = processingEnvironment.getTypeUtils(); TypeElement collectionElement = (TypeElement) types.asElement(typeMirror()); if (collectionElement != null) { ElementValidator validator = new ElementValidator(collectionElement, processingEnvironment); if (Mirrors.isInstance(types, collectionElement, List.class)) { builderClass = ListAttributeBuilder.class; } else if (Mirrors.isInstance(types, collectionElement, Set.class)) { builderClass = SetAttributeBuilder.class; } else if (Mirrors.isInstance(types, collectionElement, Iterable.class)) { builderClass = ResultAttributeBuilder.class; } else { validator.error("Invalid collection type, must be Set, List or Iterable"); } return validator; } return null; }
Example #2
Source File: AttributeBuilderReflection.java From immutables with Apache License 2.0 | 6 votes |
/** * Returns true if there's a public way to build the value type with an instance no-arg method. * * @param attribute value attribute to check. * @param possibleBuildMethod method which matches {@link StyleMirror#attributeBuilder()} * @return true if this is the possibleBuildMethod can build the value type. */ private static boolean isPossibleBuildMethod(ValueAttribute attribute, Element possibleBuildMethod) { if (possibleBuildMethod.getKind() != ElementKind.METHOD) { return false; } if (!attribute.containingType.names().possibleAttributeBuilder(possibleBuildMethod.getSimpleName())) { return false; } Types typeUtils = attribute.containingType.constitution.protoclass() .environment() .processing() .getTypeUtils(); ExecutableElement candidateBuildMethod = (ExecutableElement) possibleBuildMethod; return !candidateBuildMethod.getModifiers().contains(Modifier.STATIC) && candidateBuildMethod.getModifiers().contains(Modifier.PUBLIC) && candidateBuildMethod.getTypeParameters().isEmpty() && candidateBuildMethod.getReturnType().getKind() == TypeKind.DECLARED && typeUtils.isSameType(candidateBuildMethod.getReturnType(), attribute.containedTypeElement.asType()); }
Example #3
Source File: DelegateAssignabilityChecker.java From netbeans with Apache License 2.0 | 6 votes |
@Override protected boolean handleBothTypeVars( TypeMirror argType, TypeMirror varTypeArg, Types types ) { /* * Implementation of spec item : * the delegate type parameter and the bean type parameter are both * type variables and the upper bound of the bean type * parameter is assignable to the upper bound, * if any, of the delegate type parameter */ TypeMirror upper = ((TypeVariable)argType).getUpperBound(); TypeMirror upperVar = ((TypeVariable)varTypeArg).getUpperBound(); if ( upperVar == null || upperVar.getKind() == TypeKind.NULL ){ return true; } if ( upper == null || upper.getKind() == TypeKind.NULL ){ return false; } return checkIsAssignable(types, upper, upperVar); }
Example #4
Source File: TurbineProcessingEnvironment.java From turbine with Apache License 2.0 | 6 votes |
public TurbineProcessingEnvironment( Filer filer, Types types, Elements elements, Messager messager, Map<String, String> processorOptions, SourceVersion sourceVersion, @Nullable ClassLoader processorLoader, Map<String, byte[]> statistics) { this.filer = filer; this.types = types; this.processorOptions = processorOptions; this.sourceVersion = sourceVersion; this.elements = elements; this.statistics = statistics; this.messager = messager; this.processorLoader = processorLoader; }
Example #5
Source File: JpaControllerUtil.java From netbeans with Apache License 2.0 | 6 votes |
public static TypeMirror stripCollection(TypeMirror passedType, Types types) { if (TypeKind.DECLARED != passedType.getKind() || !(passedType instanceof DeclaredType)) { return passedType; } TypeElement passedTypeElement = (TypeElement) types.asElement(passedType); String passedTypeQualifiedName = passedTypeElement.getQualifiedName().toString(); //does not include type parameter info Class passedTypeClass = null; try { passedTypeClass = Class.forName(passedTypeQualifiedName); } catch (ClassNotFoundException e) { //just let passedTypeClass be null } if (passedTypeClass != null && Collection.class.isAssignableFrom(passedTypeClass)) { List<? extends TypeMirror> passedTypeArgs = ((DeclaredType)passedType).getTypeArguments(); if (passedTypeArgs.isEmpty()) { return passedType; } return passedTypeArgs.get(0); } return passedType; }
Example #6
Source File: PullUpTransformer.java From netbeans with Apache License 2.0 | 6 votes |
private boolean deepSearchTypes(DeclaredType currentElement, TypeMirror orig, TypeMirror something, Map<TypeMirror, TypeParameterElement> mappings) { Types types = workingCopy.getTypes(); List<? extends TypeMirror> directSupertypes = types.directSupertypes(currentElement); for (TypeMirror superType : directSupertypes) { DeclaredType type = (DeclaredType) superType; List<? extends TypeMirror> typeArguments = type.getTypeArguments(); for (int i = 0; i < typeArguments.size(); i++) { TypeMirror typeArgument = typeArguments.get(i); if (something.equals(typeArgument)) { TypeElement asElement = (TypeElement) type.asElement(); mappings.put(orig, asElement.getTypeParameters().get(i)); if (types.erasure(targetType.asType()).equals(types.erasure(superType))) { return true; } if(deepSearchTypes(type, orig, typeArgument, mappings)) { break; } } } if (types.erasure(targetType.asType()).equals(types.erasure(superType))) { mappings.remove(orig); return true; } } return false; }
Example #7
Source File: ImportAnalysisTest.java From netbeans with Apache License 2.0 | 6 votes |
public void testAddImport3() throws IOException { JavaSource src = getJavaSource(testFile); Task<WorkingCopy> task = new Task<WorkingCopy>() { public void run(WorkingCopy workingCopy) throws IOException { workingCopy.toPhase(Phase.RESOLVED); CompilationUnitTree cut = workingCopy.getCompilationUnit(); TreeMaker make = workingCopy.getTreeMaker(); ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0); MethodTree node = (MethodTree) clazz.getMembers().get(0); BlockTree body = node.getBody(); List<StatementTree> stats = new ArrayList<StatementTree>(); for (StatementTree st : body.getStatements()) { stats.add(st); } TypeElement list = workingCopy.getElements().getTypeElement("java.util.List"); TypeElement collection = workingCopy.getElements().getTypeElement("java.util.Collection"); Types types = workingCopy.getTypes(); TypeMirror tm = types.getDeclaredType(list, types.erasure(collection.asType())); stats.add(make.Variable(make.Modifiers(Collections.<Modifier>emptySet()), "utilList", make.Type(tm), null)); workingCopy.rewrite(body, make.Block(stats, false)); } }; src.runModificationTask(task).commit(); assertFiles("testAddImport3.pass"); }
Example #8
Source File: MoreTypes.java From auto-parcel with Apache License 2.0 | 6 votes |
/** * Resolves a {@link VariableElement} parameter to a method or constructor based on the given * container, or a member of a class. For parameters to a method or constructor, the variable's * enclosing element must be a supertype of the container type. For example, given a * {@code container} of type {@code Set<String>}, and a variable corresponding to the {@code E e} * parameter in the {@code Set.add(E e)} method, this will return a TypeMirror for {@code String}. */ public static TypeMirror asMemberOf(Types types, DeclaredType container, VariableElement variable) { if (variable.getKind().equals(ElementKind.PARAMETER)) { ExecutableElement methodOrConstructor = MoreElements.asExecutable(variable.getEnclosingElement()); ExecutableType resolvedMethodOrConstructor = MoreTypes.asExecutable( types.asMemberOf(container, methodOrConstructor)); List<? extends VariableElement> parameters = methodOrConstructor.getParameters(); List<? extends TypeMirror> parameterTypes = resolvedMethodOrConstructor.getParameterTypes(); checkState(parameters.size() == parameterTypes.size()); for (int i = 0; i < parameters.size(); i++) { // We need to capture the parameter type of the variable we're concerned about, // for later printing. This is the only way to do it since we can't use // types.asMemberOf on variables of methods. if (parameters.get(i).equals(variable)) { return parameterTypes.get(i); } } throw new IllegalStateException("Could not find variable: " + variable); } else { return types.asMemberOf(container, variable); } }
Example #9
Source File: RetroFacebookProcessor.java From RetroFacebook with Apache License 2.0 | 6 votes |
private String getSerialVersionUID(TypeElement type) { Types typeUtils = processingEnv.getTypeUtils(); TypeMirror serializable = getTypeMirror(Serializable.class); if (typeUtils.isAssignable(type.asType(), serializable)) { List<VariableElement> fields = ElementFilter.fieldsIn(type.getEnclosedElements()); for (VariableElement field : fields) { if (field.getSimpleName().toString().equals("serialVersionUID")) { Object value = field.getConstantValue(); if (field.getModifiers().containsAll(Arrays.asList(Modifier.STATIC, Modifier.FINAL)) && field.asType().getKind() == TypeKind.LONG && value != null) { return value + "L"; } else { errorReporter.reportError( "serialVersionUID must be a static final long compile-time constant", field); break; } } } } return ""; }
Example #10
Source File: ModelUtils.java From FreeBuilder with Apache License 2.0 | 6 votes |
private static boolean signatureMatches( ExecutableElement method, Types types, String name, TypeMirror... params) { if (!method.getSimpleName().contentEquals(name)) { return false; } if (method.getParameters().size() != params.length) { return false; } for (int i = 0; i < params.length; ++i) { TypeMirror expected = types.erasure(params[i]); TypeMirror actual = types.erasure(method.getParameters().get(i).asType()); if (!types.isSameType(expected, actual)) { return false; } } return true; }
Example #11
Source File: RenameConstructor.java From netbeans with Apache License 2.0 | 6 votes |
@Override public List<Fix> run(CompilationInfo compilationInfo, String diagnosticKey, int offset, TreePath treePath, Data<Void> data) { if (treePath.getLeaf().getKind() == Kind.METHOD) { MethodTree mt = (MethodTree) treePath.getLeaf(); TreePath parentPath = treePath.getParentPath(); ClassTree ct = (ClassTree) parentPath.getLeaf(); Trees trees = compilationInfo.getTrees(); Types types = compilationInfo.getTypes(); TreeUtilities tu = compilationInfo.getTreeUtilities(); TypeMirror type = types.erasure(trees.getTypeMirror(treePath)); if (!Utilities.isValidType(type)) { return null; } for (Tree member : ct.getMembers()) { TreePath memberPath = new TreePath(parentPath, member); if (member.getKind() == Kind.METHOD && "<init>".contentEquals(((MethodTree)member).getName()) //NOI18N && !tu.isSynthetic(memberPath) && types.isSameType(types.erasure(trees.getTypeMirror(memberPath)), type)) { return null; } } RenameConstructorFix fix = new RenameConstructorFix(compilationInfo.getSnapshot().getSource(), TreePathHandle.create(treePath, compilationInfo), offset, mt.getName(), ct.getSimpleName()); return Collections.<Fix>singletonList(fix); } return null; }
Example #12
Source File: ClassVisitorDriverFromElement.java From buck with Apache License 2.0 | 6 votes |
/** * @param targetVersion the class file version to target, expressed as the corresponding Java * source version * @param messager * @param types * @param includeParameterMetadata */ ClassVisitorDriverFromElement( SourceVersion targetVersion, ElementsExtended elements, Messager messager, Types types, boolean includeParameterMetadata) { this.targetVersion = targetVersion; this.elements = elements; descriptorFactory = new DescriptorFactory(elements); this.messager = messager; this.types = types; this.includeParameterMetadata = includeParameterMetadata; signatureFactory = new SignatureFactory(descriptorFactory); accessFlagsUtils = new AccessFlags(elements); }
Example #13
Source File: ProcessorUtils.java From nalu with Apache License 2.0 | 5 votes |
public boolean supertypeHasGeneric(Types types, TypeMirror typeMirror, TypeMirror implementsMirror) { TypeMirror superTypeMirror = this.getFlattenedSupertype(types, typeMirror, implementsMirror); if (superTypeMirror == null) { return false; } return superTypeMirror.toString() .contains("<"); }
Example #14
Source File: ProcessorUtils.java From nalu with Apache License 2.0 | 5 votes |
/** * checks if a class or interface is implemented. * * @param types types * @param typeMirror of the class to check * @param toImplement the type mirror to implement * @return true - class is implemented */ public boolean extendsClassOrInterface(Types types, TypeMirror typeMirror, TypeMirror toImplement) { String clearedToImplement = this.removeGenericsFromClassName(toImplement.toString()); Set<TypeMirror> setOfSuperType = this.getFlattenedSupertypeHierarchy(types, typeMirror); for (TypeMirror mirror : setOfSuperType) { if (clearedToImplement.equals(this.removeGenericsFromClassName(mirror.toString()))) { return true; } } return false; }
Example #15
Source File: EventAssignabilityChecker.java From netbeans with Apache License 2.0 | 5 votes |
@Override protected boolean handleRequiredRawType( Types types, List<? extends TypeMirror> typeArguments, TypeElement objectElement ) { /* Variable type is a raw. * From the spec for event type : A parameterized event type * is considered assignable to a raw observed event type * if the raw types are identical. */ return true; }
Example #16
Source File: ProcessorUtils.java From RxGroups with Apache License 2.0 | 5 votes |
static boolean isResubscribingObserver(Element observerFieldElement, Types typeUtil, Elements elementUtil) { final TypeMirror autoResubscribingTypeMirror = elementUtil.getTypeElement( AutoResubscribingObserver.class.getCanonicalName()).asType(); return typeUtil.isAssignable(observerFieldElement.asType(), typeUtil.erasure( autoResubscribingTypeMirror)); }
Example #17
Source File: AttributeFieldValidation.java From qpid-broker-j with Apache License 2.0 | 5 votes |
@Override public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv) { Elements elementUtils = processingEnv.getElementUtils(); Types typeUtils = processingEnv.getTypeUtils(); TypeElement annotationElement = elementUtils.getTypeElement(MANAGED_ATTRIBUTE_FIELD_CLASS_NAME); for (Element e : roundEnv.getElementsAnnotatedWith(annotationElement)) { for(AnnotationMirror am : e.getAnnotationMirrors()) { if(typeUtils.isSameType(am.getAnnotationType(), annotationElement.asType())) { for(Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : am.getElementValues().entrySet()) { String elementName = entry.getKey().getSimpleName().toString(); if(elementName.equals("beforeSet") || elementName.equals("afterSet")) { String methodName = entry.getValue().getValue().toString(); if(!"".equals(methodName)) { TypeElement parent = (TypeElement) e.getEnclosingElement(); if(!containsMethod(parent, methodName)) { processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Could not find method '" + methodName + "' which is defined as the " + elementName + " action", e); } } } } } } } return false; }
Example #18
Source File: TypeSimplifier.java From SimpleWeibo with Apache License 2.0 | 5 votes |
private static Set<String> ambiguousNames(Types typeUtils, Set<TypeMirror> types) { Set<String> ambiguous = new HashSet<String>(); Set<String> simpleNames = new HashSet<String>(); for (TypeMirror type : types) { if (type.getKind() == TypeKind.ERROR) { throw new MissingTypeException(); } String simpleName = typeUtils.asElement(type).getSimpleName().toString(); if (!simpleNames.add(simpleName)) { ambiguous.add(simpleName); } } return ambiguous; }
Example #19
Source File: ProbingEnvironment.java From revapi with Apache License 2.0 | 5 votes |
@Nonnull @Override @SuppressWarnings("ConstantConditions") public Types getTypeUtils() { if (processingEnvironment == null) { throw new IllegalStateException("Types instance not yet available. It is too early to call this method." + " Wait until after the archives are visited and the API model constructed."); } return new MissingTypeAwareDelegatingTypes(processingEnvironment.getTypeUtils()); }
Example #20
Source File: ScopeTest.java From openjdk-8-source with GNU General Public License v2.0 | 5 votes |
private static void verifyLambdaScopeCorrect(final String packageClause) throws Exception { JavacTool tool = JavacTool.create(); JavaFileObject source = new SimpleJavaFileObject(URI.create("mem://Test.java"), Kind.SOURCE) { @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { return packageClause + SOURCE_CODE; } @Override public boolean isNameCompatible(String simpleName, Kind kind) { return true; } }; Iterable<? extends JavaFileObject> fos = Collections.singletonList(source); JavacTask task = tool.getTask(null, null, null, new ArrayList<String>(), null, fos); final Types types = JavacTypes.instance(((JavacTaskImpl) task).getContext()); final Trees trees = Trees.instance(task); CompilationUnitTree cu = task.parse().iterator().next(); task.analyze(); new TreePathScanner<Void, Void>() { @Override public Void visitMemberSelect(MemberSelectTree node, Void p) { if (node.getIdentifier().contentEquals("correct")) { TypeMirror xType = trees.getTypeMirror(new TreePath(getCurrentPath(), node.getExpression())); Scope scope = trees.getScope(getCurrentPath()); for (Element l : scope.getLocalElements()) { if (!l.getSimpleName().contentEquals("x")) continue; if (!types.isSameType(xType, l.asType())) { throw new IllegalStateException("Incorrect variable type in scope: " + l.asType() + "; should be: " + xType); } } } return super.visitMemberSelect(node, p); } }.scan(cu, null); }
Example #21
Source File: AbstractTypesTest.java From javapoet with Apache License 2.0 | 5 votes |
@Test public void wildcardMirrorExtendsType() throws Exception { Types types = getTypes(); Elements elements = getElements(); TypeMirror charSequence = elements.getTypeElement(CharSequence.class.getName()).asType(); WildcardType wildcard = types.getWildcardType(charSequence, null); TypeName type = TypeName.get(wildcard); assertThat(type.toString()).isEqualTo("? extends java.lang.CharSequence"); }
Example #22
Source File: ContentHeaderAnnotationValidator.java From qpid-broker-j with Apache License 2.0 | 5 votes |
private boolean isValidType(TypeMirror type) { Types typeUtils = processingEnv.getTypeUtils(); Elements elementUtils = processingEnv.getElementUtils(); Element typeElement = typeUtils.asElement(type); if (VALID_PRIMITIVE_TYPES.contains(type.getKind())) { return true; } for (TypeKind primitive : VALID_PRIMITIVE_TYPES) { if (typeUtils.isSameType(type, typeUtils.boxedClass(typeUtils.getPrimitiveType(primitive)).asType())) { return true; } } if (typeElement != null && typeElement.getKind() == ElementKind.ENUM) { return true; } if (typeUtils.isSameType(type, elementUtils.getTypeElement("java.lang.String").asType())) { return true; } return false; }
Example #23
Source File: DeserializerBuilder.java From domino-jackson with Apache License 2.0 | 5 votes |
DeserializerBuilder(Types typeUtils, TypeMirror beanType, String packageName, Element field, TypeMirror fieldType) { super(typeUtils); this.beanType = beanType; this.field = field; this.fieldType = fieldType; this.packageName = packageName; }
Example #24
Source File: ProcessorUtils.java From nalu with Apache License 2.0 | 5 votes |
public TypeMirror getFlattenedSupertype(Types types, TypeMirror typeMirror, TypeMirror implementsMirror) { String implementsMirrorWihoutGeneric = this.removeGenericsFromClassName(implementsMirror.toString()); Set<TypeMirror> implementedSuperTypes = this.getFlattenedSupertypeHierarchy(types, typeMirror); for (TypeMirror typeMirrorSuperType : implementedSuperTypes) { String tn1WithoutGenric = this.removeGenericsFromClassName(typeMirrorSuperType.toString()); if (implementsMirrorWihoutGeneric.equals(tn1WithoutGenric)) { return typeMirrorSuperType; } } return null; }
Example #25
Source File: MakeSafeTypeVisitor.java From jdk8u60 with GNU General Public License v2.0 | 5 votes |
@Override public TypeMirror visitDeclared(DeclaredType t, Types types) { if (TypeModeler.isSubElement((TypeElement) t.asElement(), collectionType) || TypeModeler.isSubElement((TypeElement) t.asElement(), mapType)) { Collection<? extends TypeMirror> args = t.getTypeArguments(); TypeMirror[] safeArgs = new TypeMirror[args.size()]; int i = 0; for (TypeMirror arg : args) { safeArgs[i++] = visit(arg, types); } return types.getDeclaredType((TypeElement) t.asElement(), safeArgs); } return types.erasure(t); }
Example #26
Source File: ToolTipAnnotation.java From netbeans with Apache License 2.0 | 5 votes |
/** * Test if typeElement is a parent of currentElement. */ private static boolean testParentOf(Types types, TypeMirror currentElement, TypeMirror typeMirror) { List<? extends TypeMirror> directSupertypes = types.directSupertypes(currentElement); for (TypeMirror superType : directSupertypes) { if (superType.equals(typeMirror)) { return true; } else { boolean isParent = testParentOf(types, superType, typeMirror); if (isParent) { return true; } } } return false; }
Example #27
Source File: JavadocCompletionQuery.java From netbeans with Apache License 2.0 | 5 votes |
private static TypeMirror asMemberOf(Element element, TypeMirror type, Types types) { TypeMirror ret = element.asType(); TypeMirror enclType = element.getEnclosingElement().asType(); if (enclType.getKind() == TypeKind.DECLARED) enclType = types.erasure(enclType); while(type != null && type.getKind() == TypeKind.DECLARED) { if (types.isSubtype(type, enclType)) { ret = types.asMemberOf((DeclaredType)type, element); break; } type = ((DeclaredType)type).getEnclosingType(); } return ret; }
Example #28
Source File: Env.java From jdk8u60 with GNU General Public License v2.0 | 5 votes |
void init(DocTrees trees, Elements elements, Types types) { this.trees = trees; this.elements = elements; this.types = types; java_lang_Error = elements.getTypeElement("java.lang.Error").asType(); java_lang_RuntimeException = elements.getTypeElement("java.lang.RuntimeException").asType(); java_lang_Throwable = elements.getTypeElement("java.lang.Throwable").asType(); java_lang_Void = elements.getTypeElement("java.lang.Void").asType(); }
Example #29
Source File: ElementsService.java From netbeans with Apache License 2.0 | 5 votes |
protected ElementsService(Context context) { context.put(KEY, this); jctypes = com.sun.tools.javac.code.Types.instance(context); names = Names.instance(context); types = JavacTypes.instance(context); allowDefaultMethods = SourceLevelUtils.allowDefaultMethods(Source.instance(context)); }
Example #30
Source File: MakeSafeTypeVisitor.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
@Override public TypeMirror visitDeclared(DeclaredType t, Types types) { if (TypeModeler.isSubElement((TypeElement) t.asElement(), collectionType) || TypeModeler.isSubElement((TypeElement) t.asElement(), mapType)) { Collection<? extends TypeMirror> args = t.getTypeArguments(); TypeMirror[] safeArgs = new TypeMirror[args.size()]; int i = 0; for (TypeMirror arg : args) { safeArgs[i++] = visit(arg, types); } return types.getDeclaredType((TypeElement) t.asElement(), safeArgs); } return types.erasure(t); }