当前位置: 首页>>代码示例>>Java>>正文


Java Types.isAssignable方法代码示例

本文整理汇总了Java中javax.lang.model.util.Types.isAssignable方法的典型用法代码示例。如果您正苦于以下问题:Java Types.isAssignable方法的具体用法?Java Types.isAssignable怎么用?Java Types.isAssignable使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在javax.lang.model.util.Types的用法示例。


在下文中一共展示了Types.isAssignable方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: visitCatch

import javax.lang.model.util.Types; //导入方法依赖的package包/类
@Override
public Boolean visitCatch(CatchTree tree, Stack<Tree> d) {
    TypeMirror type1 = info.getTrees().getTypeMirror(new TreePath(new TreePath(getCurrentPath(), tree.getParameter()), tree.getParameter().getType()));
    Types t = info.getTypes();
    
    if (type1 != null) {
        Set<TypeMirror> toRemove = new HashSet<TypeMirror>();
        Map<TypeMirror, List<Tree>> exceptions2Highlights = exceptions2HighlightsStack.peek();
        
        if (exceptions2Highlights != null) {
            for (TypeMirror type2 : exceptions2Highlights.keySet()) {
                if (t.isAssignable(type2, type1)) {
                    toRemove.add(type2);
                }
            }
            
            for (TypeMirror type : toRemove) {
                exceptions2Highlights.remove(type);
            }
        }
        
    }
    
    scan(tree.getParameter(), d);
    return scan(tree.getBlock(), d);
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:27,代码来源:MethodExitDetector.java

示例2: findConstructor

import javax.lang.model.util.Types; //导入方法依赖的package包/类
private static boolean findConstructor(Element el, Types t, List<TypeMirror> paramTypes) {
    boolean found = false;
    OUTER: for (ExecutableElement ee : ElementFilter.constructorsIn(el.getEnclosedElements())) {
        if (ee.isVarArgs() || ee.getParameters().size() != paramTypes.size()) {
            continue;
        }

        Iterator<? extends VariableElement> p = ee.getParameters().iterator();
        Iterator<TypeMirror> expectedType = paramTypes.iterator();

        while (p.hasNext() && expectedType.hasNext()) {
            if (!t.isAssignable(expectedType.next(), p.next().asType())) {
                continue OUTER;
            }
        }

        found = true;
        break;
    }

    return found;
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:23,代码来源:ThrowableInitCause.java

示例3: checkThrowsDocumented

import javax.lang.model.util.Types; //导入方法依赖的package包/类
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()));
                }
            }
        }
    }
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:27,代码来源:Analyzer.java

示例4: visitMethodInvocation

import javax.lang.model.util.Types; //导入方法依赖的package包/类
@Override
public Tree visitMethodInvocation(MethodInvocationTree node, Element p) {
    List<? extends ExpressionTree> arguments = node.getArguments();
    for (int i = 0; i < arguments.size(); i++) {
        ExpressionTree argument = arguments.get(i);
        Element argElement = asElement(argument); // TODO: Slow and misses ternary expressions
        if(p.equals(argElement)) {
            Element element = asElement(node);
            if (element.getKind() == ElementKind.METHOD) {
                ExecutableElement method = (ExecutableElement) element;
                VariableElement parameter = method.getParameters().get(i);
                Types types = workingCopy.getTypes();
                TypeMirror parameterType = parameter.asType();
                if(parameterType.getKind().equals(TypeKind.TYPEVAR)) {
                    TypeVariable typeVariable = (TypeVariable) parameterType;
                    TypeMirror upperBound = typeVariable.getUpperBound();
                    TypeMirror lowerBound = typeVariable.getLowerBound();
                    if(upperBound != null && !types.isSubtype(superTypeElement.asType(), upperBound)) {
                        isReplCandidate = false;
                    }
                    if(lowerBound != null && !types.isSubtype(lowerBound, superTypeElement.asType())) {
                        isReplCandidate = false;
                    }
                } else if(!types.isAssignable(superTypeElement.asType(), parameterType)) {
                    isReplCandidate = false;
                }
            }
        }
    }
    return super.visitMethodInvocation(node, p);
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:32,代码来源:VarUsageVisitor.java

示例5: getMatchingExecutables

import javax.lang.model.util.Types; //导入方法依赖的package包/类
private List<Pair<ExecutableElement, ExecutableType>> getMatchingExecutables(TypeMirror type, Iterable<? extends Element> elements, String name, TypeMirror[] argTypes, Types types) {
    List<Pair<ExecutableElement, ExecutableType>> ret = new ArrayList<>();
    for (Element e : elements) {
        if ((e.getKind() == CONSTRUCTOR || e.getKind() == METHOD) && name.contentEquals(e.getSimpleName())) {
            List<? extends VariableElement> params = ((ExecutableElement) e).getParameters();
            int parSize = params.size();
            boolean varArgs = ((ExecutableElement) e).isVarArgs();
            if (!varArgs && (parSize < argTypes.length)) {
                continue;
            }
            ExecutableType eType = (ExecutableType) asMemberOf(e, type, types);
            if (parSize == 0) {
                ret.add(Pair.of((ExecutableElement) e, eType));
            } else {
                Iterator<? extends TypeMirror> parIt = eType.getParameterTypes().iterator();
                TypeMirror param = null;
                for (int i = 0; i <= argTypes.length; i++) {
                    if (parIt.hasNext()) {
                        param = parIt.next();
                        if (!parIt.hasNext() && param.getKind() == TypeKind.ARRAY) {
                            param = ((ArrayType) param).getComponentType();
                        }
                    } else if (!varArgs) {
                        break;
                    }
                    if (i == argTypes.length) {
                        ret.add(Pair.of((ExecutableElement) e, eType));
                        break;
                    }
                    if (argTypes[i] == null || !types.isAssignable(argTypes[i], param)) {
                        break;
                    }
                }
            }
        }
    }
    return ret;
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:39,代码来源:JavaCompletionTask.java

示例6: verifyHintMethod

import javax.lang.model.util.Types; //导入方法依赖的package包/类
private boolean verifyHintMethod(ExecutableElement method) {
    StringBuilder error = new StringBuilder();
    Elements elements = processingEnv.getElementUtils();
    TypeElement errDesc = elements.getTypeElement("org.netbeans.spi.editor.hints.ErrorDescription");
    TypeElement jlIterable = elements.getTypeElement("java.lang.Iterable");
    TypeElement hintCtx = elements.getTypeElement("org.netbeans.spi.java.hints.HintContext");

    if (errDesc == null || jlIterable == null || hintCtx == null) {
        return true;
    }

    Types types = processingEnv.getTypeUtils();
    TypeMirror errDescType = errDesc.asType(); //no type params, no need to erasure
    TypeMirror jlIterableErrDesc = types.getDeclaredType(jlIterable, errDescType);
    TypeMirror ret = method.getReturnType();

    if (!types.isSameType(ret, errDescType) && !types.isAssignable(ret, jlIterableErrDesc)) {
        error.append(ERR_RETURN_TYPE);
        error.append("\n");
    }

    if (method.getParameters().size() != 1 || !types.isSameType(method.getParameters().get(0).asType(), hintCtx.asType())) {
        error.append(ERR_PARAMETERS);
        error.append("\n");
    }

    if (!method.getModifiers().contains(Modifier.STATIC)) {
        error.append(ERR_MUST_BE_STATIC);
        error.append("\n");
    }

    if (error.length() == 0) {
        return true;
    }

    if (error.charAt(error.length() - 1) == '\n') {
        error.delete(error.length() - 1, error.length());
    }

    processingEnv.getMessager().printMessage(Kind.ERROR, error.toString(), method);

    return false;
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:44,代码来源:JavaHintsAnnotationProcessor.java

示例7: visitVariable

import javax.lang.model.util.Types; //导入方法依赖的package包/类
@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);
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:64,代码来源:UseSuperTypeRefactoringPlugin.java

示例8: isAssignable

import javax.lang.model.util.Types; //导入方法依赖的package包/类
private boolean isAssignable(TypeElement typeFrom, TypeElement typeTo) {
    Types types = workingCopy.getTypes();
    return types.isAssignable(typeFrom.asType(), typeTo.asType());
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:5,代码来源:VarUsageVisitor.java

示例9: getMatchingParams

import javax.lang.model.util.Types; //导入方法依赖的package包/类
private List<List<String>> getMatchingParams(CompilationInfo info, TypeMirror type, Iterable<? extends Element> elements, String name, TypeMirror[] argTypes, Types types) {
    List<List<String>> ret = new ArrayList<>();
    TypeUtilities tu = info.getTypeUtilities();
    for (Element e : elements) {
        if ((e.getKind() == CONSTRUCTOR || e.getKind() == METHOD) && name.contentEquals(e.getSimpleName())) {
            List<? extends VariableElement> params = ((ExecutableElement) e).getParameters();
            int parSize = params.size();
            boolean varArgs = ((ExecutableElement) e).isVarArgs();
            if (!varArgs && (parSize < argTypes.length)) {
                continue;
            }
            if (parSize == 0) {
                ret.add(Collections.<String>singletonList(NbBundle.getMessage(JavaCompletionTask.class, "JCP-no-parameters")));
            } else {
                ExecutableType eType = (ExecutableType) asMemberOf(e, type, types);
                Iterator<? extends TypeMirror> parIt = eType.getParameterTypes().iterator();
                TypeMirror param = null;
                for (int i = 0; i <= argTypes.length; i++) {
                    if (parIt.hasNext()) {
                        param = parIt.next();
                        if (!parIt.hasNext() && param.getKind() == TypeKind.ARRAY) {
                            param = ((ArrayType) param).getComponentType();
                        }
                    } else if (!varArgs) {
                        break;
                    }
                    if (i == argTypes.length) {
                        List<String> paramStrings = new ArrayList<>(parSize);
                        Iterator<? extends TypeMirror> tIt = eType.getParameterTypes().iterator();
                        for (Iterator<? extends VariableElement> it = params.iterator(); it.hasNext();) {
                            VariableElement ve = it.next();
                            StringBuilder sb = new StringBuilder();
                            sb.append(tu.getTypeName(tIt.next()));
                            if (varArgs && !tIt.hasNext()) {
                                sb.delete(sb.length() - 2, sb.length()).append("..."); //NOI18N
                            }
                            CharSequence veName = ve.getSimpleName();
                            if (veName != null && veName.length() > 0) {
                                sb.append(" "); // NOI18N
                                sb.append(veName);
                            }
                            if (it.hasNext()) {
                                sb.append(", "); // NOI18N
                            }
                            paramStrings.add(sb.toString());
                        }
                        ret.add(paramStrings);
                        break;
                    }
                    if (argTypes[i] == null || argTypes[i].getKind() != TypeKind.ERROR && !types.isAssignable(argTypes[i], param)) {
                        break;
                    }
                }
            }
        }
    }
    return ret.isEmpty() ? null : ret;
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:59,代码来源:JavaTooltipTask.java

示例10: visitThrows

import javax.lang.model.util.Types; //导入方法依赖的package包/类
@Override
    public Void visitThrows(ThrowsTree tree, List<ErrorDescription> errors) {
        boolean oldInheritDoc = foundInheritDoc;
        ReferenceTree exName = tree.getExceptionName();
        DocTreePath refPath = new DocTreePath(getCurrentPath(), tree.getExceptionName());
        Element ex = javac.getDocTrees().getElement(refPath);
        Types types = javac.getTypes();
        Elements elements = javac.getElements();
        final TypeElement throwableEl = elements.getTypeElement("java.lang.Throwable");
        final TypeElement errorEl = elements.getTypeElement("java.lang.Error");
        final TypeElement runtimeEl = elements.getTypeElement("java.lang.RuntimeException");
        if(throwableEl == null || errorEl == null || runtimeEl == null) {
            LOG.warning("Broken java-platform, cannot resolve " + throwableEl == null? "java.lang.Throwable" : errorEl == null? "java.lang.Error" : "java.lang.RuntimeException"); //NOI18N
            return null;
        }
        TypeMirror throwable = throwableEl.asType();
        TypeMirror error = errorEl.asType();
        TypeMirror runtime = runtimeEl.asType();
        DocTreePath currentDocPath = getCurrentPath();
        DocTreePathHandle dtph = DocTreePathHandle.create(currentDocPath, javac);
        if(dtph == null) {
            return null;
        }
        DocSourcePositions sp = (DocSourcePositions) javac.getTrees().getSourcePositions();
        int start = (int) sp.getStartPosition(javac.getCompilationUnit(), currentDocPath.getDocComment(), tree);
        int end = (int) sp.getEndPosition(javac.getCompilationUnit(), currentDocPath.getDocComment(), tree);
        if (ex == null || (ex.asType().getKind() == TypeKind.DECLARED
                && types.isAssignable(ex.asType(), throwable))) {
            switch (currentElement.getKind()) {
                case CONSTRUCTOR:
                case METHOD:
                    if (ex == null || !(types.isAssignable(ex.asType(), error)
                            || types.isAssignable(ex.asType(), runtime))) {
                        ExecutableElement ee = (ExecutableElement) currentElement;
                        String fqn;
                        if (ex != null) {
                            fqn = ((TypeElement) ex).getQualifiedName().toString();
                        } else {
                            ExpressionTree referenceClass = javac.getTreeUtilities().getReferenceClass(new DocTreePath(currentDocPath, exName));
                            if(referenceClass == null) break;
                            fqn = referenceClass.toString();
                        }
                        checkThrowsDeclared(tree, ex, fqn, ee.getThrownTypes(), dtph, start, end, errors);
                    }
                    break;
                default:
//                        env.messages.error(REFERENCE, tree, "dc.invalid.throws");
            }
        } else {
//                env.messages.error(REFERENCE, tree, "dc.invalid.throws");
        }
        warnIfEmpty(tree, tree.getDescription());
        super.visitThrows(tree, errors);
        foundInheritDoc = oldInheritDoc;
        return null;
    }
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:57,代码来源:Analyzer.java

示例11: check

import javax.lang.model.util.Types; //导入方法依赖的package包/类
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);
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:54,代码来源:ValidBasicType.java

示例12: implementsInterface

import javax.lang.model.util.Types; //导入方法依赖的package包/类
public static boolean implementsInterface(Elements elementUtils, Types typeUtils, Element element, Class<?> clazz) {
    TypeMirror classType = elementUtils.getTypeElement(clazz.getName()).asType();
    return typeUtils.isAssignable(element.asType(), classType);
}
 
开发者ID:jzallas,项目名称:LifecycleAware,代码行数:5,代码来源:Utils.java

示例13: process

import javax.lang.model.util.Types; //导入方法依赖的package包/类
@Override
public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment environment) {
    for(final Element element : environment.getElementsAnnotatedWith(Put.class)) {
        final Put annotation = element.getAnnotation(Put.class);

        if(ElementKind.METHOD != element.getKind()) {
            throw new DataSinkDefinitionException(
                "Must use @Put with methods only! Tried to use with " + element.getSimpleName()
                    + ", which is not a method.");
        }

        final Set<Modifier> modifiers = element.getModifiers();
        if(!modifiers.contains(Modifier.PUBLIC)) {
            throw new DataSinkDefinitionException(
                "Must use @Put with public methods only! Tried to use with " + element.getSimpleName()
                    + ", which is not public.");
        }
        if(modifiers.contains(Modifier.STATIC)) {
            throw new DataSinkDefinitionException(
                "Must use @Put with non-static methods only! Tried to use with " + element.getSimpleName()
                    + ", which is static.");
        }

        final ExecutableType method = (ExecutableType)element.asType();
        final Types types = processingEnv.getTypeUtils();
        final Elements elements = processingEnv.getElementUtils();

        // annotation.value() will throw the exception because it doesn't have compiled class information yet, and is of type Class<?>.
        TypeMirror annotatedType = null;
        try {
            annotation.value();
        } catch(final MirroredTypeException e) {
            annotatedType = e.getTypeMirror();
        }

        if(TypeKind.VOID != method.getReturnType().getKind()) {
            throw new DataSinkDefinitionException(
                "@Put method must have void return! Tried to use with " + element.getSimpleName() + ", which returns "
                    + method.getReturnType() + ".");
        }
        if(method.getParameterTypes().size() != 2) {
            throw new DataSinkDefinitionException("@Put methods must take 2 arguments: T item, PipelineContext context. Tried to use with "
                + element.getSimpleName() + ", which has a different signature.");
        }

        final TypeMirror contextType = elements.getTypeElement(PipelineContext.class.getName()).asType();

        if(!types.isAssignable(annotatedType, method.getParameterTypes().get(0))) {
            throw new DataSinkDefinitionException(
                "@Put method annotated value type must be assignable from the method's first argument type. Tried to use with "
                    + element.getSimpleName() + ", which takes " + method.getParameterTypes().get(0) + ".");
        }
        if(!types.isAssignable(method.getParameterTypes().get(1), contextType)) {
            throw new DataSinkDefinitionException("@Put method second argument must be assignable from " + contextType + ". Tried to use with "
                + element.getSimpleName() + ", which takes " + method.getParameterTypes().get(1) + ".");
        }
    }

    return true;
}
 
开发者ID:meraki-analytics,项目名称:datapipelines-java,代码行数:61,代码来源:PutProcessor.java

示例14: process

import javax.lang.model.util.Types; //导入方法依赖的package包/类
@Override
public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment environment) {
    for(final Element element : environment.getElementsAnnotatedWith(PutMany.class)) {
        final PutMany annotation = element.getAnnotation(PutMany.class);

        if(ElementKind.METHOD != element.getKind()) {
            throw new DataSinkDefinitionException(
                "Must use @PutMany with methods only! Tried to use with " + element.getSimpleName()
                    + ", which is not a method.");
        }

        final Set<Modifier> modifiers = element.getModifiers();
        if(!modifiers.contains(Modifier.PUBLIC)) {
            throw new DataSinkDefinitionException(
                "Must use @PutMany with public methods only! Tried to use with " + element.getSimpleName()
                    + ", which is not public.");
        }
        if(modifiers.contains(Modifier.STATIC)) {
            throw new DataSinkDefinitionException(
                "Must use @PutMany with non-static methods only! Tried to use with " + element.getSimpleName()
                    + ", which is static.");
        }

        final ExecutableType method = (ExecutableType)element.asType();
        final Types types = processingEnv.getTypeUtils();
        final Elements elements = processingEnv.getElementUtils();

        // annotation.value() will throw the exception because it doesn't have compiled class information yet, and is of type Class<?>.
        TypeMirror annotatedType = null;
        try {
            annotation.value();
        } catch(final MirroredTypeException e) {
            annotatedType = e.getTypeMirror();
        }

        if(TypeKind.VOID != method.getReturnType().getKind()) {
            throw new DataSinkDefinitionException("@PutMany method must have void return! Tried to use with " + element.getSimpleName() + ", which returns "
                + method.getReturnType() + ".");
        }
        if(method.getParameterTypes().size() != 2) {
            throw new DataSinkDefinitionException("@PutMany methods must take 2 arguments: Iterable<T> items, PipelineContext context. Tried to use with "
                + element.getSimpleName() + ", which has a different signature.");
        }

        final TypeElement iterableType = elements.getTypeElement(Iterable.class.getName());
        final TypeMirror[] genericType = new TypeMirror[] {annotatedType};
        final DeclaredType itemsType = types.getDeclaredType(iterableType, genericType);
        final TypeMirror contextType = elements.getTypeElement(PipelineContext.class.getName()).asType();

        if(!types.isAssignable(itemsType, method.getParameterTypes().get(0))) {
            throw new DataSinkDefinitionException(
                "@PutMany method annotated value must be assignable from the generic type of the method's first argument . Tried to use with "
                    + element.getSimpleName() + ", which takes " + method.getParameterTypes().get(0) + ".");
        }
        if(!types.isAssignable(method.getParameterTypes().get(1), contextType)) {
            throw new DataSinkDefinitionException("@PutMany method second argument must be assignable from " + contextType + ". Tried to use with "
                + element.getSimpleName() + ", which takes " + method.getParameterTypes().get(1) + ".");
        }
    }

    return true;
}
 
开发者ID:meraki-analytics,项目名称:datapipelines-java,代码行数:63,代码来源:PutManyProcessor.java

示例15: process

import javax.lang.model.util.Types; //导入方法依赖的package包/类
@Override
public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment environment) {
    for(final Element element : environment.getElementsAnnotatedWith(GetMany.class)) {
        final GetMany annotation = element.getAnnotation(GetMany.class);

        if(ElementKind.METHOD != element.getKind()) {
            throw new DataSourceDefinitionException(
                "Must use @GetMany with methods only! Tried to use with " + element.getSimpleName()
                    + ", which is not a method.");
        }

        final Set<Modifier> modifiers = element.getModifiers();
        if(!modifiers.contains(Modifier.PUBLIC)) {
            throw new DataSourceDefinitionException(
                "Must use @GetMany with public methods only! Tried to use with " + element.getSimpleName()
                    + ", which is not public.");
        }
        if(modifiers.contains(Modifier.STATIC)) {
            throw new DataSourceDefinitionException(
                "Must use @GetMany with non-static methods only! Tried to use with " + element.getSimpleName()
                    + ", which is static.");
        }

        final ExecutableType method = (ExecutableType)element.asType();
        final Types types = processingEnv.getTypeUtils();
        final Elements elements = processingEnv.getElementUtils();

        // annotation.value() will throw the exception because it doesn't have compiled class information yet, and is of type Class<?>.
        TypeMirror annotatedType = null;
        try {
            annotation.value();
        } catch(final MirroredTypeException e) {
            annotatedType = e.getTypeMirror();
        }

        final TypeElement closeableIteratorType = elements.getTypeElement(CloseableIterator.class.getName());
        final DeclaredType returnType = types.getDeclaredType(closeableIteratorType, annotatedType);

        if(!types.isAssignable(method.getReturnType(), returnType)) {
            throw new DataSourceDefinitionException(
                "@GetMany methods must return a CloseableIterator over a type which is assignable from the annotation value. Tried to use with "
                    + element.getSimpleName() + ", which returns " + method.getReturnType() + ".");
        }
        if(method.getParameterTypes().size() != 2) {
            throw new DataSourceDefinitionException(
                "@GetMany methods must take 2 arguments: Map<String, Object> query, PipelineContext context. Tried to use with "
                    + element.getSimpleName() + ", which has a different signature.");
        }

        final TypeMirror stringType = elements.getTypeElement(String.class.getName()).asType();
        final TypeMirror objectType = elements.getTypeElement(Object.class.getName()).asType();
        final TypeElement mapType = elements.getTypeElement(Map.class.getName());
        final TypeMirror[] genericTypes = new TypeMirror[] {stringType, objectType};
        final DeclaredType queryType = types.getDeclaredType(mapType, genericTypes);
        final TypeMirror contextType = elements.getTypeElement(PipelineContext.class.getName()).asType();

        if(!types.isAssignable(method.getParameterTypes().get(0), queryType)) {
            throw new DataSourceDefinitionException("@GetMany method first argument must be assignable from " + queryType + ". Tried to use with "
                + element.getSimpleName() + ", which takes " + method.getParameterTypes().get(0) + ".");
        }
        if(!types.isAssignable(method.getParameterTypes().get(1), contextType)) {
            throw new DataSourceDefinitionException("@GetMany method second argument must be assignable from " + contextType + ". Tried to use with "
                + element.getSimpleName() + ", which takes " + method.getParameterTypes().get(1) + ".");
        }
    }

    return true;
}
 
开发者ID:meraki-analytics,项目名称:datapipelines-java,代码行数:69,代码来源:GetManyProcessor.java


注:本文中的javax.lang.model.util.Types.isAssignable方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。