Example usage for javax.lang.model.element TypeElement getInterfaces

List of usage examples for javax.lang.model.element TypeElement getInterfaces

Introduction

In this page you can find the example usage for javax.lang.model.element TypeElement getInterfaces.

Prototype

List<? extends TypeMirror> getInterfaces();

Source Link

Document

Returns the interface types directly implemented by this class or extended by this interface.

Usage

From source file:org.lambdamatic.mongodb.apt.template.ElementUtils.java

/**
 * Checks if the given {@link Element} is, implements or extends the given target type.
 * /*from  ww  w  . j  ava2s. c o  m*/
 * @param type the element to analyze
 * @param targetType the type to check
 * @return <code>true</code> if the given {@link Element} corresponds to a type that implements
 *         {@link List}, <code>false</code> otherwise.
 */
public static boolean isAssignable(final DeclaredType type, final Class<?> targetType) {
    if (type instanceof NoType) {
        return false;
    }
    if (type.asElement().toString().equals(targetType.getName())) {
        return true;
    }
    final TypeElement element = (TypeElement) type.asElement();
    final boolean implementation = element.getInterfaces().stream()
            .filter(interfaceMirror -> interfaceMirror.getKind() == TypeKind.DECLARED)
            .map(interfaceMirror -> (DeclaredType) interfaceMirror)
            .map(declaredInterface -> declaredInterface.asElement())
            .anyMatch(declaredElement -> declaredElement.toString().equals(targetType.getName()));
    if (implementation) {
        return true;
    }
    if (element.getSuperclass().getKind() == TypeKind.DECLARED) {
        return isAssignable((DeclaredType) (element.getSuperclass()), targetType);
    }
    return false;
}

From source file:Main.java

public static boolean checkIfIsSerializable(ProcessingEnvironment processingEnvironment, String type) {
    if (type.equals("java.lang.String") || type.equals("java.lang.Boolean")
            || type.equals("java.lang.Character")) {
        //it is serializable but we handle it different way
        return false;
    }/*from w  w  w  .j a  v  a2s . c  o m*/

    TypeElement serializableElement = processingEnvironment.getElementUtils()
            .getTypeElement("java.io.Serializable");
    TypeElement elementType;

    elementType = processingEnvironment.getElementUtils().getTypeElement(type);

    if (elementType != null) {
        for (TypeMirror typeMirror : elementType.getInterfaces()) {
            if (typeMirror.toString().equals(serializableElement.toString())) {
                return true;
            }
        }
    }
    return false;
}

From source file:Main.java

public static boolean checkIfIsParcelable(ProcessingEnvironment processingEnvironment, String type) {
    TypeElement parcelableElement = processingEnvironment.getElementUtils()
            .getTypeElement("android.os.Parcelable");
    TypeElement elementType;
    if (type.contains("<") && type.contains(">")) {
        elementType = processingEnvironment.getElementUtils()
                .getTypeElement(type.substring(type.indexOf("<") + 1, type.indexOf(">")));
    } else {/* w  w w  .j  a v  a  2  s .  com*/
        elementType = processingEnvironment.getElementUtils()
                .getTypeElement(type.replace("[]", "").replace(">", ""));
    }
    if (elementType != null) {
        for (TypeMirror typeMirror : elementType.getInterfaces()) {
            if (typeMirror.toString().equals(parcelableElement.toString())) {
                return true;
            }
        }
    }
    return false;
}

From source file:io.github.jeddict.jpa.modeler.properties.convert.ConvertPanel.java

static void importAttributeConverter(String classHandle, AtomicBoolean validated, ModelerFile modelerFile) {
    if (StringUtils.isBlank(classHandle)) {
        validated.set(true);/* www  . j  a  va 2s  .  c  o  m*/
        return;
    }
    FileObject pkg = findSourceGroupForFile(modelerFile.getFileObject()).getRootFolder();
    try {
        JavaSource javaSource = JavaSource.create(ClasspathInfo.create(pkg));
        javaSource.runUserActionTask(controller -> {
            try {
                controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
                TypeElement jc = controller.getElements().getTypeElement(classHandle);
                EntityMappings entityMappings = (EntityMappings) modelerFile.getDefinitionElement();
                Optional<Converter> converter = entityMappings.findConverter(classHandle);
                if (jc != null) {
                    DeclaredType attributeConverterType = null;
                    if (!jc.getInterfaces().isEmpty()) { //fetch interface info
                        for (TypeMirror interfaceType : jc.getInterfaces()) {
                            if (interfaceType.getKind() == TypeKind.DECLARED && AttributeConverter.class
                                    .getName().equals(((DeclaredType) interfaceType).asElement().toString())) {
                                attributeConverterType = (DeclaredType) interfaceType;
                            }
                        }
                    }
                    if (attributeConverterType != null
                            && attributeConverterType.getTypeArguments().size() == 2) {
                        TypeMirror attributeType = attributeConverterType.getTypeArguments().get(0);
                        TypeMirror dbFieldType = attributeConverterType.getTypeArguments().get(1);
                        if (!entityMappings.addConverter(classHandle, attributeType.toString(),
                                dbFieldType.toString())) {
                            message("MSG_ATTRIBUTE_CONVERTER_TYPE_CONFLICT", classHandle);
                        } else {
                            if (!converter.isPresent()) {
                                message("MSG_ATTRIBUTE_CONVERTER_TYPE_REGISTERED", classHandle,
                                        attributeType.toString(), dbFieldType.toString());
                            }
                            validated.set(true);
                        }
                    } else {
                        message("MSG_ATTRIBUTE_CONVERTER_NOT_IMPLEMENTED", classHandle);
                    }
                } else {
                    if (converter.isPresent()) {
                        validated.set(true);
                    } else {
                        message("MSG_ARTIFACT_NOT_FOUND", classHandle, pkg.getPath());
                    }
                }
            } catch (IOException t) {
                ExceptionUtils.printStackTrace(t);
            }
        }, true);
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
}

From source file:org.netbeans.jpa.modeler.properties.convert.ConvertPanel.java

static void importAttributeConverter(String classHandle, AtomicBoolean validated, ModelerFile modelerFile) {
    if (StringUtils.isBlank(classHandle)) {
        validated.set(true);/*from  w  w  w .j av  a  2 s  . co  m*/
        return;
    }
    FileObject pkg = SourceGroupSupport.findSourceGroupForFile(modelerFile.getFileObject()).getRootFolder();
    try {
        JavaSource javaSource = JavaSource.create(ClasspathInfo.create(pkg));
        javaSource.runUserActionTask(controller -> {
            try {
                controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
                TypeElement jc = controller.getElements().getTypeElement(classHandle);
                EntityMappings entityMappings = (EntityMappings) modelerFile.getDefinitionElement();
                Optional<Converter> converter = entityMappings.findConverter(classHandle);
                if (jc != null) {
                    DeclaredType attributeConverterType = null;
                    if (!jc.getInterfaces().isEmpty()) { //fetch interface info
                        for (TypeMirror interfaceType : jc.getInterfaces()) {
                            if (interfaceType.getKind() == TypeKind.DECLARED && AttributeConverter.class
                                    .getName().equals(((DeclaredType) interfaceType).asElement().toString())) {
                                attributeConverterType = (DeclaredType) interfaceType;
                            }
                        }
                    }
                    if (attributeConverterType != null
                            && attributeConverterType.getTypeArguments().size() == 2) {
                        TypeMirror attributeType = attributeConverterType.getTypeArguments().get(0);
                        TypeMirror dbFieldType = attributeConverterType.getTypeArguments().get(1);
                        if (!entityMappings.addConverter(classHandle, attributeType.toString(),
                                dbFieldType.toString())) {
                            message("MSG_ATTRIBUTE_CONVERTER_TYPE_CONFLICT", classHandle);
                        } else {
                            if (!converter.isPresent()) {
                                message("MSG_ATTRIBUTE_CONVERTER_TYPE_REGISTERED", classHandle,
                                        attributeType.toString(), dbFieldType.toString());
                            }
                            validated.set(true);
                        }
                    } else {
                        message("MSG_ATTRIBUTE_CONVERTER_NOT_IMPLEMENTED", classHandle);
                    }
                } else {
                    if (converter.isPresent()) {
                        validated.set(true);
                    } else {
                        message("MSG_ARTIFACT_NOT_FOUND", classHandle, pkg.getPath());
                    }
                }
            } catch (IOException t) {
                ExceptionUtils.printStackTrace(t);
            }
        }, true);
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
}

From source file:com.contentful.vault.compiler.Processor.java

private boolean isSubtypeOfType(TypeMirror typeMirror, String otherType) {
    if (otherType.equals(typeMirror.toString())) {
        return true;
    }/* w ww .j ava 2  s .c  o m*/
    if (!(typeMirror instanceof DeclaredType)) {
        return false;
    }
    DeclaredType declaredType = (DeclaredType) typeMirror;
    List<? extends TypeMirror> typeArguments = declaredType.getTypeArguments();
    if (typeArguments.size() > 0) {
        StringBuilder typeString = new StringBuilder(declaredType.asElement().toString());
        typeString.append('<');
        for (int i = 0; i < typeArguments.size(); i++) {
            if (i > 0) {
                typeString.append(',');
            }
            typeString.append('?');
        }
        typeString.append('>');
        if (typeString.toString().equals(otherType)) {
            return true;
        }
    }
    Element element = declaredType.asElement();
    if (!(element instanceof TypeElement)) {
        return false;
    }
    TypeElement typeElement = (TypeElement) element;
    TypeMirror superType = typeElement.getSuperclass();
    if (isSubtypeOfType(superType, otherType)) {
        return true;
    }
    for (TypeMirror interfaceType : typeElement.getInterfaces()) {
        if (isSubtypeOfType(interfaceType, otherType)) {
            return true;
        }
    }
    return false;
}

From source file:org.leandreck.endpoints.processor.model.EndpointNodeFactory.java

private List<MethodNode> defineMethods(final TypeElement typeElement, final DeclaredType containingType) {
    final TypeMirror superclass = typeElement.getSuperclass();
    final List<MethodNode> superclassMethods;
    if (DECLARED.equals(superclass.getKind()) && !"java.lang.Object".equals(superclass.toString())) {
        superclassMethods = defineMethods((TypeElement) ((DeclaredType) superclass).asElement(),
                containingType);// w  w  w. j  a va 2  s  .  c o m
    } else {
        superclassMethods = new ArrayList<>(20);
    }

    //Implemented Interfaces:
    typeElement.getInterfaces().stream()
            .flatMap(
                    it -> defineMethods((TypeElement) ((DeclaredType) it).asElement(), containingType).stream())
            .forEach(superclassMethods::add);

    //Own enclosed Methods
    ElementFilter.methodsIn(typeElement.getEnclosedElements()).stream()
            .map(methodElement -> methodNodeFactory.createMethodNode(methodElement, containingType))
            .filter(method -> !method.isIgnored()).forEach(superclassMethods::add);
    return superclassMethods;
}

From source file:org.netbeans.jpa.modeler.spec.extend.JavaClass.java

@Override
public void load(EntityMappings entityMappings, TypeElement element, boolean fieldAccess) {
    this.setId(NBModelerUtil.getAutoGeneratedStringId());

    this.clazz = element.getSimpleName().toString();
    if (element.getModifiers().contains(Modifier.ABSTRACT)) {
        this.setAbstract(true);
    }//from  w ww  .  j a  v a 2 s  .c om
    for (TypeMirror mirror : element.getInterfaces()) {
        if (Serializable.class.getName().equals(mirror.toString())) {
            continue;
        }
        this.addInterface(mirror.toString());
    }
    this.setAnnotation(JavaSourceParserUtil.getNonEEAnnotation(element));
}

From source file:uniol.apt.compiler.AbstractServiceProcessor.java

private boolean isValidClass(Element ele) {
    if (ele.getKind() != ElementKind.CLASS) {
        error(ele, "Non-Class %s annotated with %s.", ele.getSimpleName().toString(),
                this.annotationClass.getCanonicalName());
    }/*from w  ww.j  a  va 2s .c  om*/

    TypeElement classEle = (TypeElement) ele;

    if (!classEle.getModifiers().contains(Modifier.PUBLIC)) {
        error(classEle, "Class %s is not public.", classEle.getQualifiedName().toString());
        return false;
    }

    if (classEle.getModifiers().contains(Modifier.ABSTRACT)) {
        error(classEle, "Class %s is abstract.", classEle.getQualifiedName().toString());
        return false;
    }

    TypeMirror expected = this.types.erasure(this.elements.getTypeElement(this.interfaceName).asType());
    boolean found = false;
    for (TypeMirror actual : classEle.getInterfaces()) {
        if (this.types.isAssignable(actual, expected)) {
            found = true;
            break;
        }
    }
    if (!found) {
        error(classEle, "Class %s doesn't implement interface %s.", classEle.getQualifiedName().toString(),
                this.interfaceName);
        return false;
    }

    if (!allowGenerics && !classEle.getTypeParameters().isEmpty()) {
        error(classEle, "Class %s is generic.", classEle.getQualifiedName().toString());
        return false;
    }

    for (Element enclosed : classEle.getEnclosedElements()) {
        if (enclosed.getKind() == ElementKind.CONSTRUCTOR) {
            ExecutableElement constructorEle = (ExecutableElement) enclosed;
            if (constructorEle.getParameters().size() == 0
                    && constructorEle.getModifiers().contains(Modifier.PUBLIC)) {
                return true;
            }
        }
    }

    error(classEle, String.format("Class %s needs an public no-arg constructor",
            classEle.getQualifiedName().toString()));
    return false;
}

From source file:org.androidtransfuse.adapter.element.ASTElementFactory.java

private ASTType buildType(TypeElement typeElement) {
    log.debug("ASTElementType building: " + typeElement.getQualifiedName());
    //build placeholder for ASTElementType and contained data structures to allow for children population
    //while avoiding back link loops
    PackageClass packageClass = buildPackageClass(typeElement);

    if (blacklist.containsKey(packageClass)) {
        return blacklist.get(packageClass);
    }/*from   w w w.  j  a  v a2s . co  m*/

    ASTTypeVirtualProxy astTypeProxy = new ASTTypeVirtualProxy(packageClass);
    typeCache.put(typeElement, astTypeProxy);

    ASTType superClass = null;
    if (typeElement.getSuperclass() != null) {
        superClass = typeElement.getSuperclass().accept(astTypeBuilderVisitor, null);
    }

    ImmutableSet<ASTType> interfaces = FluentIterable.from(typeElement.getInterfaces())
            .transform(astTypeBuilderVisitor).toSet();

    ImmutableSet.Builder<ASTAnnotation> annotations = ImmutableSet.builder();
    ImmutableSet.Builder<ASTConstructor> constructors = ImmutableSet.builder();
    ImmutableSet.Builder<ASTField> fields = ImmutableSet.builder();
    ImmutableSet.Builder<ASTMethod> methods = ImmutableSet.builder();

    //iterate and build the contained elements within this TypeElement
    annotations.addAll(getAnnotations(typeElement));
    constructors.addAll(transformAST(typeElement.getEnclosedElements(), ASTConstructor.class));
    fields.addAll(transformAST(typeElement.getEnclosedElements(), ASTField.class));
    methods.addAll(transformAST(typeElement.getEnclosedElements(), ASTMethod.class));

    ASTType astType = new ASTElementType(buildAccessModifier(typeElement), packageClass, typeElement,
            constructors.build(), methods.build(), fields.build(), superClass, interfaces, annotations.build());

    astTypeProxy.load(astType);

    return astType;
}