Java Code Examples for javax.lang.model.util.Types#isAssignable()
The following examples show how to use
javax.lang.model.util.Types#isAssignable() .
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: PipelineAnnotationsProcessor.java From datacollector-api with Apache License 2.0 | 6 votes |
private StageType extractStageType(TypeMirror stageType) { Types typeUtils = processingEnv.getTypeUtils(); StageType type; if (typeUtils.isAssignable(stageType, typeOfSource) || typeUtils.isAssignable(stageType, typeOfPushSource)) { type = StageType.SOURCE; } else if (typeUtils.isSubtype(stageType, typeOfProcessor)) { type = StageType.PROCESSOR; } else if (typeUtils.isSubtype(stageType, typeOfExecutor)) { type = StageType.EXECUTOR; } else if (typeUtils.isSubtype(stageType, typeOfTarget)) { type = StageType.TARGET; } else { type = null; } return type; }
Example 2
Source File: PaperParcelDescriptor.java From paperparcel with Apache License 2.0 | 6 votes |
private static Optional<ExecutableElement> getSetterMethod( Types types, VariableElement field, ImmutableSet<ExecutableElement> allMethods) { String fieldName = field.getSimpleName().toString(); TypeMirror fieldType = Utils.replaceTypeVariablesWithUpperBounds(types, field.asType()); for (ExecutableElement method : allMethods) { List<? extends VariableElement> parameters = method.getParameters(); if (parameters.size() == 1 && isSetterMethod(fieldName, method.getSimpleName().toString()) && method.getTypeParameters().size() == 0 && types.isAssignable(Utils.replaceTypeVariablesWithUpperBounds( types, parameters.get(0).asType()), fieldType)) { return Optional.of(method); } } return Optional.absent(); }
Example 3
Source File: OperationAnnotationValidator.java From qpid-broker-j with Apache License 2.0 | 6 votes |
public void checkInterfaceExtendsConfiguredObject(final TypeElement annotationElement, final Element e) { Types typeUtils = processingEnv.getTypeUtils(); TypeMirror configuredObjectType = getErasure("org.apache.qpid.server.model.ConfiguredObject"); TypeElement parent = (TypeElement) e.getEnclosingElement(); if (!typeUtils.isAssignable(typeUtils.erasure(parent.asType()), configuredObjectType)) { processingEnv.getMessager() .printMessage(Diagnostic.Kind.ERROR, "@" + annotationElement.getSimpleName() + " can only be applied to methods within an interface which extends " + configuredObjectType.toString() + " which does not apply to " + parent.asType().toString(), e); } }
Example 4
Source File: ContentHeaderAnnotationValidator.java From qpid-broker-j with Apache License 2.0 | 6 votes |
private void checkClassExtendsContent(TypeElement annotationElement, Element e) { Types typeUtils = processingEnv.getTypeUtils(); TypeMirror contentType = getErasure(CONTENT_CLASS_NAME); TypeElement parent = (TypeElement) e.getEnclosingElement(); if (!typeUtils.isAssignable(typeUtils.erasure(parent.asType()), contentType)) { processingEnv.getMessager() .printMessage(Diagnostic.Kind.ERROR, "@" + annotationElement.getSimpleName() + " can only be applied to methods within a class implementing " + contentType.toString() + " which does not apply to " + parent.asType().toString(), e); } }
Example 5
Source File: Analyzer.java From netbeans with Apache License 2.0 | 6 votes |
private void checkThrowsDocumented(List<? extends TypeMirror> list, List<? extends ExpressionTree> trees, DocTreePath docTreePath, Set<String> inheritedThrows, List<ErrorDescription> errors) { if(foundInheritDoc) return; for (int i = 0; i < list.size(); i++) { if(ctx.isCanceled()) { return; } TypeMirror e = list.get(i); Tree t = trees.get(i); Types types = javac.getTypes(); if (!foundThrows.contains(e) && !inheritedThrows.contains(e.toString()) && (!(types.isAssignable(e, javac.getElements().getTypeElement("java.lang.Error").asType()) || types.isAssignable(e, javac.getElements().getTypeElement("java.lang.RuntimeException").asType())))) { boolean found = false; for (TypeMirror typeMirror : foundThrows) { if(types.isAssignable(typeMirror, e)) { found = true; break; } } if(!found) { DocTreePathHandle dtph = DocTreePathHandle.create(docTreePath, javac); if(dtph != null) { errors.add(ErrorDescriptionFactory.forTree(ctx, t, NbBundle.getMessage(Analyzer.class, "MISSING_THROWS_DESC", e.toString()), AddTagFix.createAddThrowsTagFix(dtph, e.toString(), i).toEditorFix())); } } } } }
Example 6
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 7
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 8
Source File: ProcessorUtils.java From RxGroups with Apache License 2.0 | 5 votes |
static boolean isAutoTaggable(Element observerFieldElement, Types typeUtil, Elements elementUtil) { final TypeMirror autoResubscribingTypeMirror = elementUtil.getTypeElement( AutoTaggableObserver.class.getCanonicalName()).asType(); return typeUtil.isAssignable(observerFieldElement.asType(), typeUtil.erasure( autoResubscribingTypeMirror)); }
Example 9
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 10
Source File: ManagedAnnotationValidator.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_ANNOTATION_CLASS_NAME); String className = "org.apache.qpid.server.model.ManagedInterface"; TypeMirror configuredObjectType = getErasure(className); for (Element e : roundEnv.getElementsAnnotatedWith(annotationElement)) { if (e.getKind() != ElementKind.INTERFACE) { processingEnv.getMessager() .printMessage(Diagnostic.Kind.ERROR, "@" + annotationElement.getSimpleName() + " can only be applied to an interface", e ); } if(!typeUtils.isAssignable(typeUtils.erasure(e.asType()), configuredObjectType)) { processingEnv.getMessager() .printMessage(Diagnostic.Kind.ERROR, "@" + annotationElement.getSimpleName() + " can only be applied to an interface which extends " + className, e ); } } return false; }
Example 11
Source File: AttributeAnnotationValidator.java From qpid-broker-j with Apache License 2.0 | 5 votes |
static boolean isNamed(ProcessingEnvironment processingEnv, final TypeMirror type) { Types typeUtils = processingEnv.getTypeUtils(); String className = "org.apache.qpid.server.model.Named"; TypeMirror namedType = getErasure(processingEnv, className); return typeUtils.isAssignable(typeUtils.erasure(type), namedType); }
Example 12
Source File: FunctionalType.java From FreeBuilder with Apache License 2.0 | 4 votes |
private static boolean isAssignable(TypeMirror fromParam, TypeMirror toParam, Types types) { if (isVoid(fromParam) || isVoid(toParam)) { return isVoid(fromParam) && isVoid(toParam); } return types.isAssignable(fromParam, toParam); }
Example 13
Source File: VarUsageVisitor.java From netbeans with Apache License 2.0 | 4 votes |
private boolean isAssignable(TypeElement typeFrom, TypeElement typeTo) { Types types = workingCopy.getTypes(); return types.isAssignable(typeFrom.asType(), typeTo.asType()); }
Example 14
Source File: ValidBasicType.java From netbeans with Apache License 2.0 | 4 votes |
public Collection<ErrorDescription> check(JPAProblemContext ctx, HintContext hc, AttributeWrapper attrib) { if (!(attrib.getModelElement() instanceof Basic)) { return null; } TreeUtilities treeUtils = ctx.getCompilationInfo().getTreeUtilities(); Types types = ctx.getCompilationInfo().getTypes(); TypeMirror attrType = attrib.getType(); TypeMirror typeSerializable = treeUtils.parseType("java.io.Serializable", //NOI18N ctx.getJavaClass()); TypeMirror typeEnum = treeUtils.parseType("java.lang.Enum", //NOI18N ctx.getJavaClass()); TypeMirror typeCollection = treeUtils.parseType("java.util.Collection", //NOI18N ctx.getJavaClass()); if (types.isAssignable(attrType, typeSerializable) || types.isAssignable(attrType, typeEnum) || types.isAssignable(attrType, typeCollection)) { return null; } for (String typeName : fixedBasicTypes) { TypeMirror type = treeUtils.parseType(typeName, ctx.getJavaClass()); if (type != null && types.isSameType(attrType, type)) { return null; } } if (Utilities.hasAnnotation(attrib.getJavaElement(), JPAAnnotations.ELEMENT_COLLECTION)) { //according to annotation it's not basic type and need to be verified in appropriate validator return null; } if (Utilities.hasAnnotation(attrib.getJavaElement(), JPAAnnotations.EMBEDDED)) { //@Embedded, see also #167419 return null; } Tree elementTree = ctx.getCompilationInfo().getTrees().getTree(attrib.getJavaElement()); Utilities.TextSpan underlineSpan = Utilities.getUnderlineSpan( ctx.getCompilationInfo(), elementTree); ErrorDescription error = ErrorDescriptionFactory.forSpan( hc, underlineSpan.getStartOffset(), underlineSpan.getEndOffset(), NbBundle.getMessage(ValidBasicType.class, "MSG_ValidBasicType"));//TODO: may need to have "error" as default return Collections.singleton(error); }
Example 15
Source File: EnableBeansFilter.java From netbeans with Apache License 2.0 | 4 votes |
private boolean checkClass( TypeElement element ){ if ( element.getKind() != ElementKind.CLASS ){ return false; } Set<Modifier> modifiers = element.getModifiers(); Element enclosing = element.getEnclosingElement(); if ( !( enclosing instanceof PackageElement) ){ /* * If class is inner class then it should be static. */ if ( !modifiers.contains( Modifier.STATIC ) ){ return false; } } Elements elements = getHelper().getCompilationController().getElements(); Types types = getHelper().getCompilationController().getTypes(); List<? extends AnnotationMirror> allAnnotations = elements. getAllAnnotationMirrors(element); if ( modifiers.contains( Modifier.ABSTRACT ) && !getHelper().hasAnnotation(allAnnotations, DECORATOR ) ) { /* * If class is abstract it should be Decorator. */ return false; } TypeElement extensionElement = elements.getTypeElement( EXTENSION ); if ( extensionElement!= null ){ TypeMirror extensionType = extensionElement.asType(); /* * Class doesn't implement Extension */ if ( types.isAssignable( element.asType(), extensionType )){ return false; } } /* * There should be either no parameters CTOR or CTOR is annotated with @Inject */ List<ExecutableElement> constructors = ElementFilter.constructorsIn( element.getEnclosedElements()); boolean foundCtor = constructors.size() ==0; for (ExecutableElement ctor : constructors) { if ( ctor.getParameters().size() == 0 ){ foundCtor = true; break; } if ( getHelper().hasAnnotation(allAnnotations, FieldInjectionPointLogic.INJECT_ANNOTATION)) { foundCtor = true; break; } } return foundCtor; }
Example 16
Source File: PaperParcelDescriptor.java From paperparcel with Apache License 2.0 | 4 votes |
static WriteInfo create( TypeElement owner, Types types, FieldDescriptor.Factory fieldDescriptorFactory, ImmutableList<VariableElement> fields, ImmutableSet<ExecutableElement> methods, ImmutableList<ExecutableElement> constructors, ImmutableList<String> reflectAnnotations) throws NonWritableFieldsException { ImmutableMap<String, VariableElement> fieldNamesToField = fieldNamesToField(fields); ImmutableMap.Builder<ExecutableElement, ImmutableList<VariableElement>> allNonWritableFieldsMapBuilder = ImmutableMap.builder(); ImmutableMap.Builder<ExecutableElement, ImmutableList<VariableElement>> unassignableConstructorParameterMapBuilder = ImmutableMap.builder(); for (ExecutableElement constructor : constructors) { // Create a mutable copy of fieldNamesToField so we can remove elements from it as we iterate // to keep track of which elements we have seen Map<String, VariableElement> nonConstructorFieldsMap = new LinkedHashMap<>(fieldNamesToField); ImmutableList.Builder<VariableElement> unassignableParametersBuilder = ImmutableList.builder(); ImmutableList.Builder<FieldDescriptor> constructorFieldDescriptorsBuilder = ImmutableList.builder(); // Iterate over parameters and check two things: // 1) The parameter has a field with the same name // 2) The parameter type is assignable to the field List<? extends VariableElement> parameters = constructor.getParameters(); for (VariableElement parameter : parameters) { String parameterName = parameter.getSimpleName().toString(); // All wildcards need to be stripped from the parameter type as a work around // for kotlin data classes generating non-assignable constructor parameters // with generic types. TypeMirror parameterType = Utils.replaceTypeVariablesWithUpperBounds(types, parameter.asType()); VariableElement fieldOrNull = fieldNamesToField.get(parameterName); if (fieldOrNull != null && types.isAssignable(parameterType, Utils.replaceTypeVariablesWithUpperBounds(types, fieldOrNull.asType()))) { nonConstructorFieldsMap.remove(parameterName); constructorFieldDescriptorsBuilder.add(fieldDescriptorFactory.create(owner, fieldOrNull)); } else { unassignableParametersBuilder.add(parameter); } } // Check if there were any unassignable parameters in the constructor. If so, skip. ImmutableList<VariableElement> unassignableParameters = unassignableParametersBuilder.build(); if (unassignableParameters.size() > 0) { unassignableConstructorParameterMapBuilder.put(constructor, unassignableParameters); continue; } // Check that the remaining parameters are assignable directly, or via setters. ImmutableList.Builder<VariableElement> nonWritableFieldsBuilder = ImmutableList.builder(); ImmutableList<VariableElement> nonConstructorFields = ImmutableList.copyOf(nonConstructorFieldsMap.values()); ImmutableList.Builder<FieldDescriptor> writableFieldsBuilder = ImmutableList.builder(); ImmutableMap.Builder<FieldDescriptor, ExecutableElement> setterMethodMapBuilder = ImmutableMap.builder(); for (VariableElement field : nonConstructorFields) { if (isWritableDirectly(field)) { writableFieldsBuilder.add(fieldDescriptorFactory.create(owner, field)); } else { Optional<ExecutableElement> setterMethod = getSetterMethod(types, field, methods); if (setterMethod.isPresent()) { setterMethodMapBuilder.put(fieldDescriptorFactory.create(owner, field), setterMethod.get()); } else if (Utils.usesAnyAnnotationsFrom(field, reflectAnnotations)) { writableFieldsBuilder.add(fieldDescriptorFactory.create(owner, field)); } else { nonWritableFieldsBuilder.add(field); } } } ImmutableList<VariableElement> nonWritableFields = nonWritableFieldsBuilder.build(); if (nonWritableFields.size() != 0) { // Map all of the non-writable fields to the corresponding constructor for (potential) // error handling later allNonWritableFieldsMapBuilder.put(constructor, nonWritableFields); } else { // All fields are writable using this constructor return new WriteInfo( constructorFieldDescriptorsBuilder.build(), Visibility.ofElement(constructor) != Visibility.PRIVATE, writableFieldsBuilder.build(), setterMethodMapBuilder.build()); } } // Throw an error if fields are not writable throw NonWritableFieldsException.create( allNonWritableFieldsMapBuilder.build(), unassignableConstructorParameterMapBuilder.build()); }
Example 17
Source File: UseSuperTypeRefactoringPlugin.java From netbeans with Apache License 2.0 | 4 votes |
@Override public Tree visitVariable(VariableTree varTree, Element elementToMatch) { TreePath treePath = getCurrentPath(); VariableElement varElement = (VariableElement) workingCopy. getTrees().getElement(treePath); //This check shouldn't be needed (ideally). if (varElement == null) { return super.visitVariable(varTree, elementToMatch); } TreePath parentPath = treePath.getParentPath(); if(parentPath != null && parentPath.getLeaf().getKind() == Tree.Kind.CATCH) { // Do not change in catch statement return super.visitVariable(varTree, elementToMatch); } Types types = workingCopy.getTypes(); TypeMirror varTypeErasure = types.erasure(varElement.asType()); TypeMirror elToMatchErasure = types.erasure(subTypeElement.asType()); if (types.isSameType(varTypeErasure, elToMatchErasure)) { //Check for overloaded methods boolean clashWithOverload = false; if(parentPath != null && parentPath.getLeaf().getKind() == Tree.Kind.METHOD) { Trees trees = workingCopy.getTrees(); ExecutableElement parent = (ExecutableElement) trees.getElement(parentPath); TreePath enclosing = JavaRefactoringUtils.findEnclosingClass(workingCopy, parentPath, true, true, true, true, true); TypeElement typeEl = (TypeElement) (enclosing == null? null : trees.getElement(enclosing)); if(parent != null && typeEl != null) { Name simpleName = parent.getSimpleName(); int size = parent.getParameters().size(); OUTER: for (ExecutableElement method : ElementFilter.methodsIn(workingCopy.getElements().getAllMembers(typeEl))) { if (method != parent && method.getKind() == parent.getKind() && size == method.getParameters().size() && simpleName.contentEquals(method.getSimpleName())) { for (int i = 0; i < parent.getParameters().size(); i++) { VariableElement par = parent.getParameters().get(i); TypeMirror parErasure = types.erasure(par.asType()); TypeMirror par2Erasure = types.erasure(method.getParameters().get(i).asType()); if(!types.isSameType(parErasure, par2Erasure)) { if(types.isAssignable(types.erasure(superTypeElement.asType()), par2Erasure)) { clashWithOverload = true; break OUTER; } if(types.isSubtype(parErasure, par2Erasure)) { clashWithOverload = true; break OUTER; } } } } } } } if (!clashWithOverload && isReplaceCandidate(varElement)) { replaceWithSuperType(treePath, varTree, varElement, superTypeElement); } } return super.visitVariable(varTree, elementToMatch); }
Example 18
Source File: TypeUtil.java From auto-parcel with Apache License 2.0 | 4 votes |
static boolean isClassOfType(Types typeUtils, TypeMirror type, TypeMirror cls) { return type != null && typeUtils.isAssignable(cls, type); }
Example 19
Source File: ViewValidator.java From sqlitemagic with Apache License 2.0 | 4 votes |
public boolean isViewElementValid(ViewElement viewElement) { final TypeElement rawElement = viewElement.getViewElement(); if (viewElement.getAllColumnsCount() == 0) { environment.error(rawElement, "Found no view columns in view class \"%s\". Each view must define at least one method with @%s annotation", viewElement.getViewElementName(), ViewColumn.class.getSimpleName()); return false; } if (viewElement.isMultipleQueries()) { environment.error(rawElement, ERR_MULTI_QUERY); return false; } final VariableElement queryConstant = viewElement.getQueryConstant(); if (queryConstant == null) { environment.error(rawElement, viewElement.getViewElementName() + ERR_MISSING_QUERY); return false; } if (queryConstant.getModifiers().contains(Modifier.PRIVATE)) { environment.error(queryConstant, "View query must be public static field."); return false; } final Types typeUtils = environment.getTypeUtils(); final TypeMirror queryConstantType = queryConstant.asType(); if (!queryConstantType.toString().equals("error.NonExistentClass") && !typeUtils.isAssignable(COMPILED_SELECT, typeUtils.erasure(queryConstantType))) { environment.error(queryConstant, ERR_WRONG_QUERY_TYPE); return false; } final Set<Modifier> modifiers = viewElement.getModifiers(); if (environment.hasAutoValueLib()) { if (!viewElement.isInterface() && !viewElement.isValidDataClass()) { final Class<? extends Annotation> autoValueAnnotation = environment.getAutoValueAnnotation(); if (!modifiers.contains(Modifier.ABSTRACT) || rawElement.getAnnotation(autoValueAnnotation) == null) { environment.error(rawElement, String.format(ERR_WRONG_TYPE, autoValueAnnotation.getSimpleName())); return false; } } } else { if (viewElement.isInterface()) { environment.error(rawElement, "No AutoValue library detected. @%s annotated interfaces are only supported with AutoValue library.", View.class.getSimpleName()); return false; } if (modifiers.contains(Modifier.ABSTRACT)) { environment.error(rawElement, "No AutoValue library detected. @%s annotated abstract classes are only supported with AutoValue library.", View.class.getSimpleName()); return false; } if (!viewElement.isValidDataClass()) { environment.error(rawElement, "@%s annotated classes must be valid data classes.", View.class.getSimpleName()); return false; } } return true; }
Example 20
Source File: Unbalanced.java From netbeans with Apache License 2.0 | 3 votes |
private static boolean testType(CompilationInfo info, TypeMirror actualType, String superClass) { TypeElement juCollection = info.getElements().getTypeElement(superClass); if (juCollection == null) return false; Types t = info.getTypes(); return t.isAssignable(t.erasure(actualType), t.erasure(juCollection.asType())); }