javax.lang.model.element.Element#asType ( )源码实例Demo

下面列出了javax.lang.model.element.Element#asType ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: kripton   文件: ModelProperty.java
/**
 * Instantiates a new model property.
 *
 * @param entity the entity
 * @param element the element
 * @param modelAnnotations the model annotations
 */
@SuppressWarnings("rawtypes")
public ModelProperty(ModelEntity<?> entity, Element element, List<ModelAnnotation> modelAnnotations) {
	super((element != null) ? element.getSimpleName().toString() : null, element);

	this.parent = new WeakReference<ModelEntity>(entity);

	if (element != null) {			
		TypeName temp1=TypeName.get(element.asType());			
		LiteralType temp2 = LiteralType.of(element.asType().toString());
		AssertKripton.fail((temp1 instanceof ClassName) && temp2.isCollection(), "In bean '%s' property '%s' can not use Object as parameter", entity.getElement().asType().toString() ,element.getSimpleName().toString()); 
		
		
		propertyType = new ModelType(element.asType());
		publicField = element.getModifiers().contains(Modifier.PUBLIC);
	}
	this.annotations = new ArrayList<ModelAnnotation>();
	if (modelAnnotations != null) {
		this.annotations.addAll(modelAnnotations);
	}
	this.typeAdapter = new TypeAdapter();
}
 
源代码2 项目: fit   文件: FitProcessor.java
private boolean isSetter(Element method) {
  Name methodName = method.getSimpleName();
  if (!methodName.toString().startsWith("set")) {
    return false;
  }
  ExecutableType type = (ExecutableType) method.asType();
  //返回值不为void
  if (!TypeKind.VOID.equals(type.getReturnType().getKind())) {
    return false;
  }
  //有1个参数
  if (type.getParameterTypes().size() != 1) {
    return false;
  }

  if (methodName.length() < 4) {
    return false;
  }
  return true;
}
 
源代码3 项目: fit   文件: FitProcessor.java
private boolean isGetter(Element method) {
  Name methodName = method.getSimpleName();
  if ((!methodName.toString().startsWith("get")) && !methodName.toString().startsWith("is")) {
    return false;
  }
  ExecutableType type = (ExecutableType) method.asType();
  //返回值为void
  if (TypeKind.VOID.equals(type.getReturnType().getKind())) {
    return false;
  }
  //有参数
  if (type.getParameterTypes().size() > 0) {
    return false;
  }

  if (methodName.length() < 4) {
    return false;
  }
  return true;
}
 
源代码4 项目: abtestgen   文件: ABTestProcessor.java
private void getTextTests(RoundEnvironment roundEnv, Multimap<String, ViewTestData> viewTestMap) {
  for (Element element : roundEnv.getElementsAnnotatedWith(TextTest.class)) {
    TextTest testAnnotation = element.getAnnotation(TextTest.class);
    if (element.getKind() != ElementKind.FIELD) {
      messager.printMessage(Diagnostic.Kind.ERROR, "Can only run ABView tests on a field!");
    } else {
      TypeMirror typeMirror = element.asType();
      String type = typeMirror.toString();
      TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();
      ViewTestData data =
          createABViewData(testAnnotation.testName(), testAnnotation.method(), element,
              enclosingElement, testAnnotation.values());
      viewTestMap.put(data.getTestClassPath(), data);
    }
  }
}
 
源代码5 项目: pocketknife   文件: BaseProcessor.java
protected void validateSerializer(Element element, Class<? extends Annotation> annotation, TypeMirror serializer, Class abstractSerializer) {
    if (serializer == null) {
        return;
    }
    Element absSerializerElement = elements.getTypeElement(abstractSerializer.getName());
    if (absSerializerElement == null) {
        throw new IllegalStateException(String.format("Unable to find %s type", abstractSerializer.getName()));
    }
    TypeMirror absSerializerMirror = absSerializerElement.asType();
    if (!types.isAssignable(serializer, types.erasure(absSerializerMirror))) {
        throw new IllegalStateException(String.format("@%s value must extend %s", annotation.getName(), abstractSerializer.getName()));
    }
    TypeMirror elementType = element.asType();
    for (TypeMirror superType : types.directSupertypes(serializer)) {
        if (types.isAssignable(superType, types.erasure(absSerializerMirror)) &&  superType instanceof DeclaredType) {
            if (types.isSameType(((DeclaredType) superType).getTypeArguments().get(0), elementType)) {
                return;
            } else {
                throw new IllegalStateException(String.format("Serializer T must be of type %s", elementType.toString()));
            }
        }
    }
    throw new IllegalStateException(String.format("%s must extend %s", serializer.toString(), absSerializerMirror.toString()));
}
 
源代码6 项目: netbeans   文件: InstanceRefFinder.java
@Override
public Object visitIdentifier(IdentifierTree node, Object p) {
    Element el = ci.getTrees().getElement(getCurrentPath());
    if (el == null || el.asType() == null || el.asType().getKind() == TypeKind.ERROR) {
        return null;
    }
    switch (el.getKind()) {
        case LOCAL_VARIABLE:
            addLocalClassVariable(el);
            addUsedMember(el, enclosingType);
            break;
        case TYPE_PARAMETER:
            addInstanceOfTypeParameter(el);
            break;
        case FIELD:
        case METHOD:
            addInstanceForMemberOf(el);
            break;
        case CLASS:
        case ENUM:
        case INTERFACE:
            if (node.getName().contentEquals("this") || node.getName().contentEquals("super")) {
                addInstanceForType(enclosingType);
            }
            break;
        case EXCEPTION_PARAMETER:
        case RESOURCE_VARIABLE:
            addLocalClassVariable(el);
            // fall through
        case PARAMETER:
            addInstanceOfParameterOwner(el);
            break;
        case PACKAGE:
            break;
        default:
            addUsedMember(el, enclosingType);
    }
    return super.visitIdentifier(node, p);
}
 
源代码7 项目: Witch-Android   文件: TypeUtils.java
public static String getReturnTypeDescription(Element element) {
    if (element.getKind().isField()) {
        return element.asType().toString();
    } else if (element.getKind() == ElementKind.METHOD) {
        ExecutableType ext = (ExecutableType) element.asType();
        return ext.getReturnType().toString();
    }
    return "";
}
 
源代码8 项目: netbeans   文件: ParameterInjectionPointLogic.java
static TypeMirror getParameterType( CompilationController controller, 
        Element element , DeclaredType parentType, String... interfaceFqns) 
{
    TypeMirror elementType = null;
    if ( parentType == null ) {
        elementType = element.asType();
    }
    else {
        elementType = controller.getTypes().asMemberOf(parentType, element);
    }
    return getParameterType(elementType,interfaceFqns);
}
 
源代码9 项目: YCApt   文件: RouterProcessor.java
/**-----------------------------------------注解----------------------------------------*/

    private void processorRouter(Set<? extends Element> rootElements) {
        //首先获取activity信息
        TypeElement activity = elementUtils.getTypeElement(RouterConstants.ACTIVITY);
        //获取service信息
        TypeElement service = elementUtils.getTypeElement(RouterConstants.I_SERVICE);
        //被 Router 注解的节点集合
        for (Element element : rootElements) {
            RouteMeta routeMeta;
            //类信息
            TypeMirror typeMirror = element.asType();
            log.i("RouterProcessor Route class:" + typeMirror.toString());
            //获取注解
            Router route = element.getAnnotation(Router.class);
            if (typeUtils.isSubtype(typeMirror, activity.asType())) {
                routeMeta = new RouteMeta(RouteMeta.Type.ACTIVITY, route, element);
            } else if (typeUtils.isSubtype(typeMirror, service.asType())) {
                routeMeta = new RouteMeta(RouteMeta.Type.I_SERVICE, route, element);
            } else {
                throw new RuntimeException("RouterProcessor Just support Activity or IService Route: " + element);
            }
            //检查是否配置 group 如果没有配置 则从path截取出组名
            categories(routeMeta);
        }

        //获取接口
        TypeElement iRouteGroup = elementUtils.getTypeElement(RouterConstants.I_ROUTE_GROUP);
        TypeElement iRouteRoot = elementUtils.getTypeElement(RouterConstants.I_ROUTE_ROOT);

        //生成Group记录分组表
        generatedGroup(iRouteGroup);

        //生成Root类 作用:记录<分组,对应的Group类>
        generatedRoot(iRouteRoot, iRouteGroup);
    }
 
源代码10 项目: netbeans   文件: JDIWrappersTest.java
private Element getElement(Tree tree) {
    TreePath expPath = TreePath.getPath(cut, tree);
    Element e = trees.getElement(expPath);
    if (e == null) {
        if (tree instanceof ParenthesizedTree) {
            e = getElement(((ParenthesizedTree) tree).getExpression());
            //if (e == null) {
            //    System.err.println("Have null element for "+tree);
            //}
            //System.err.println("\nHAVE "+e.asType().toString()+" for ParenthesizedTree "+tree);
        }
        else if (tree instanceof TypeCastTree) {
            e = getElement(((TypeCastTree) tree).getType());
            //if (e == null) {
            //    System.err.println("Have null element for "+tree);
            //}
            //System.err.println("\nHAVE "+e.asType().toString()+" for TypeCastTree "+tree);
        }
        else if (tree instanceof AssignmentTree) {
            e = getElement(((AssignmentTree) tree).getVariable());
        }
        else if (tree instanceof ArrayAccessTree) {
            e = getElement(((ArrayAccessTree) tree).getExpression());
            if (e != null) {
                TypeMirror tm = e.asType();
                if (tm.getKind() == TypeKind.ARRAY) {
                    tm = ((ArrayType) tm).getComponentType();
                    e = types.asElement(tm);
                }
            }
            //System.err.println("ArrayAccessTree = "+((ArrayAccessTree) tree).getExpression()+", element = "+getElement(((ArrayAccessTree) tree).getExpression())+", type = "+getElement(((ArrayAccessTree) tree).getExpression()).asType());
        }
    }
    return e;
}
 
源代码11 项目: Kratos   文件: KratosProcessor.java
private void parseLBindText(Element element, Map<TypeElement, BindingClass> targetClassMap,
                            Set<String> erasedTargetNames) {
    TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();

    TypeMirror elementType = element.asType();
    if (elementType.getKind() == TypeKind.TYPEVAR) {
        TypeVariable typeVariable = (TypeVariable) elementType;
        elementType = typeVariable.getUpperBound();
    }
    // Assemble information on the field.
    String[] ids = element.getAnnotation(LBindText.class).value();
    BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement, true, false);
    for (String id : ids) {
        if (bindingClass != null) {
            KBindings bindings = bindingClass.getKBindings(id);
            if (bindings != null) {
                Iterator<FieldViewBinding> iterator = bindings.getFieldBindings().iterator();
                if (iterator.hasNext()) {
                    FieldViewBinding existingBinding = iterator.next();
                    error(element, "Attempt to use @%s for an already bound ID %s on '%s'. (%s.%s)",
                            LBindText.class.getSimpleName(), id, existingBinding.getName(),
                            enclosingElement.getQualifiedName(), element.getSimpleName());
                    return;
                }
            }
        } else {
            bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement, true, false);
        }
        String name = element.getSimpleName().toString();
        TypeName type = TypeName.get(elementType);
        boolean required = isRequiredBinding(element);

        FieldViewBinding binding = new FieldViewBinding(name, type, required);
        bindingClass.addField(String.valueOf(id), binding);
    }

    // Add the type-erased version to the valid binding targets set.
    erasedTargetNames.add(enclosingElement.toString());
}
 
源代码12 项目: jackdaw   文件: TypeUtils.java
public static String getterName(final Element e) {
    final char[] field = getName(e).toCharArray();
    field[0] = Character.toUpperCase(field[0]);

    final TypeMirror typeMirror = e.asType();
    final TypeKind kind = typeMirror.getKind();
    final String prefix = kind == TypeKind.BOOLEAN ? "is" : "get";
    return prefix + new String(field);
}
 
源代码13 项目: AutoLayout-Android   文件: AutoLayoutProcessor.java
private void parseElement(Element element, List<ParsedInfo> infos, Class<? extends Annotation> annotationClass) {
    if (isBindingInWrongPackage(annotationClass, element)) {
        return;
    }

    TypeElement enclosingElement = (TypeElement) element;

    // Verify that the target type extends from ViewGroup.
    TypeMirror elementType = element.asType();
    if (elementType.getKind() == TypeKind.TYPEVAR) {
        TypeVariable typeVariable = (TypeVariable) elementType;
        elementType = typeVariable.getUpperBound();
    }

    if (!isSubtypeOfType(elementType, VIEW_GROUP)) {
        error(element, "@%s fields must extend from ViewGroup. (%s)",
                annotationClass.getSimpleName(), enclosingElement.getQualifiedName());
    }

    String name = element.getSimpleName().toString();
    String canonicalName = enclosingElement.getQualifiedName().toString();

    String superCanonicalName = ((TypeElement) element).getSuperclass().toString();
    String superName = superCanonicalName.substring(superCanonicalName.lastIndexOf('.') + 1);

    if (superCanonicalName.startsWith("android.widget.")) {
        superCanonicalName = superCanonicalName.substring(superCanonicalName.lastIndexOf('.') + 1);
    }

    ParsedInfo info = new ParsedInfo();
    info.name = name;
    info.canonicalName = canonicalName;
    info.superName = superName;
    info.superCanonicalName = superCanonicalName;
    infos.add(info);
}
 
源代码14 项目: netbeans   文件: ELTypeUtilities.java
public static TypeMirror getReturnTypeForGenericClass(CompilationContext info, final ExecutableElement method, ELElement elElement, List<Node> rootToNode) {
    Node node = null;
    for (int i = rootToNode.size() - 1; i > 0; i--) {
        node = rootToNode.get(i);
        if (node instanceof AstIdentifier) {
            break;
        }
    }
    if (node != null) {
        Element element = ELTypeUtilities.resolveElement(info, elElement, node);
        if (element == null) {
            return method.getReturnType();
        }

        TypeMirror type = element.asType();
        // interfaces are at the end of the List - first parameter has to be superclass
        TypeMirror directSupertype = info.info().getTypes().directSupertypes(type).get(0);
        if (directSupertype instanceof DeclaredType) {
            DeclaredType declaredType = (DeclaredType) directSupertype;
            // index of involved type argument
            int indexOfTypeArgument = -1;
            // list of all type arguments
            List<? extends TypeMirror> typeArguments = declaredType.getTypeArguments();

            // search for the same method in the generic class
            for (Element enclosedElement : declaredType.asElement().getEnclosedElements()) {
                if (method.equals(enclosedElement)) {
                    TypeMirror returnType = ((ExecutableElement) enclosedElement).getReturnType();
                    // get index of type argument which is returned by involved method
                    indexOfTypeArgument = info.info().getElementUtilities().enclosingTypeElement(method).
                            getTypeParameters().indexOf(((TypeVariable) returnType).asElement());
                    break;
                }
            }
            if (indexOfTypeArgument != -1 && indexOfTypeArgument < typeArguments.size()) {
                return typeArguments.get(indexOfTypeArgument);
            }
        }
    }

    return method.getReturnType();
}
 
源代码15 项目: butterknife   文件: ButterKnifeProcessor.java
private void parseBindView(Element element, Map<TypeElement, BindingSet.Builder> builderMap,
    Set<TypeElement> erasedTargetNames) {
  TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();

  // Start by verifying common generated code restrictions.
  boolean hasError = isInaccessibleViaGeneratedCode(BindView.class, "fields", element)
      || isBindingInWrongPackage(BindView.class, element);

  // Verify that the target type extends from View.
  TypeMirror elementType = element.asType();
  if (elementType.getKind() == TypeKind.TYPEVAR) {
    TypeVariable typeVariable = (TypeVariable) elementType;
    elementType = typeVariable.getUpperBound();
  }
  Name qualifiedName = enclosingElement.getQualifiedName();
  Name simpleName = element.getSimpleName();
  if (!isSubtypeOfType(elementType, VIEW_TYPE) && !isInterface(elementType)) {
    if (elementType.getKind() == TypeKind.ERROR) {
      note(element, "@%s field with unresolved type (%s) "
              + "must elsewhere be generated as a View or interface. (%s.%s)",
          BindView.class.getSimpleName(), elementType, qualifiedName, simpleName);
    } else {
      error(element, "@%s fields must extend from View or be an interface. (%s.%s)",
          BindView.class.getSimpleName(), qualifiedName, simpleName);
      hasError = true;
    }
  }

  if (hasError) {
    return;
  }

  // Assemble information on the field.
  int id = element.getAnnotation(BindView.class).value();
  BindingSet.Builder builder = builderMap.get(enclosingElement);
  Id resourceId = elementToId(element, BindView.class, id);
  if (builder != null) {
    String existingBindingName = builder.findExistingBindingName(resourceId);
    if (existingBindingName != null) {
      error(element, "Attempt to use @%s for an already bound ID %d on '%s'. (%s.%s)",
          BindView.class.getSimpleName(), id, existingBindingName,
          enclosingElement.getQualifiedName(), element.getSimpleName());
      return;
    }
  } else {
    builder = getOrCreateBindingBuilder(builderMap, enclosingElement);
  }

  String name = simpleName.toString();
  TypeName type = TypeName.get(elementType);
  boolean required = isFieldRequired(element);

  builder.addField(resourceId, new FieldViewBinding(name, type, required));

  // Add the type-erased version to the valid binding targets set.
  erasedTargetNames.add(enclosingElement);
}
 
@SuppressWarnings("PMD.CyclomaticComplexity") private void processAnnotatedExtraParameters(final RoundEnvironment environment, final AnnotatedMethodParameters annotatedParameters) {
    final Class<? extends Annotation> annotation = Extra.class;
    final Set<? extends Element> parameters = environment.getElementsAnnotatedWith(annotation);

    for (final Element parameter : parameters) {
        try {
            final ExecutableElement method = (ExecutableElement) parameter.getEnclosingElement();

            if (!Utils.isParameter(parameter)) {
                throw new OnActivityResultProcessingException(method, "@%s annotation must be on a method parameter", annotation.getSimpleName());
            }

            boolean didFindMatch = false;
            final AnnotatedParameter[] supportedAnnotatedParameters = AnnotatedParameter.values();

            final TypeMirror parameterTypeMirror = parameter.asType();
            final TypeName parameterType = TypeVariableName.get(parameterTypeMirror);

            for (final AnnotatedParameter annotatedParameter : supportedAnnotatedParameters) {
                if (annotatedParameter.type.equals(parameterType)) {
                    annotatedParameters.put(method, (VariableElement) parameter, annotatedParameter.createParameter(parameter));
                    didFindMatch = true;
                    break;
                }
            }

            if (!didFindMatch) {
                final boolean isImplementingParcelable = typeUtils.isAssignable(parameterTypeMirror, elementUtils.getTypeElement(AnnotatedParameter.PARCELABLE.type.toString()).asType());
                final boolean isImplementingSerializable = typeUtils.isAssignable(parameterTypeMirror, elementUtils.getTypeElement(AnnotatedParameter.SERIALIZABLE.type.toString()).asType());

                if (isImplementingParcelable) {
                    annotatedParameters.put(method, (VariableElement) parameter, AnnotatedParameter.PARCELABLE.createParameter(parameter));
                    didFindMatch = true;
                } else if (isImplementingSerializable) {
                    annotatedParameters.put(method, (VariableElement) parameter, AnnotatedParameter.SERIALIZABLE.createParameter(parameter));
                    didFindMatch = true;
                }
            }

            if (!didFindMatch) {
                throw new OnActivityResultProcessingException(method, "@%s parameter does not support type %s", annotation.getSimpleName(), parameterTypeMirror.toString());
            }
        } catch (final OnActivityResultProcessingException e) {
            e.printError(processingEnv);
        }
    }
}
 
源代码17 项目: DDComponentForAndroid   文件: RouterProcessor.java
private void parseRouteNodes(Set<? extends Element> routeElements) {

        TypeMirror type_Activity = elements.getTypeElement(ACTIVITY).asType();

        for (Element element : routeElements) {
            TypeMirror tm = element.asType();
            RouteNode route = element.getAnnotation(RouteNode.class);

            if (types.isSubtype(tm, type_Activity)) {                 // Activity
                logger.info(">>> Found activity route: " + tm.toString() + " <<<");

                Node node = new Node();
                String path = route.path();

                checkPath(path);

                node.setPath(path);
                node.setDesc(route.desc());
                node.setPriority(route.priority());
                node.setNodeType(NodeType.ACTIVITY);
                node.setRawType(element);

                Map<String, Integer> paramsType = new HashMap<>();
                Map<String, String> paramsDesc = new HashMap<>();
                for (Element field : element.getEnclosedElements()) {
                    if (field.getKind().isField() && field.getAnnotation(Autowired.class) != null) {
                        Autowired paramConfig = field.getAnnotation(Autowired.class);
                        paramsType.put(StringUtils.isEmpty(paramConfig.name())
                                ? field.getSimpleName().toString() : paramConfig.name(), typeUtils.typeExchange(field));
                        paramsDesc.put(StringUtils.isEmpty(paramConfig.name())
                                ? field.getSimpleName().toString() : paramConfig.name(), typeUtils.typeDesc(field));
                    }
                }
                node.setParamsType(paramsType);
                node.setParamsDesc(paramsDesc);

                if (!routerNodes.contains(node)) {
                    routerNodes.add(node);
                }
            } else {
                throw new IllegalStateException("only activity can be annotated by RouteNode");
            }
        }
    }
 
源代码18 项目: pocketknife   文件: BundleBindingProcessor.java
private void parseBindAnnotation(Element element, Map<TypeElement, BundleBindingAdapterGenerator> targetClassMap, Set<String> erasedTargetNames)
        throws InvalidTypeException {
    TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();

    // Verify that the target has all the appropriate information for type
    TypeMirror type = element.asType();
    if (element instanceof TypeVariable) {
        TypeVariable typeVariable = (TypeVariable) type;
        type = typeVariable.getUpperBound();
    }


    validateNotRequiredArguments(element);
    validateBindingPackage(BindArgument.class, element);
    validateForCodeGeneration(BindArgument.class, element);
    Access access = getAccess(BindArgument.class, element, enclosingElement);

    TypeMirror bundleSerializer = getAnnotationElementClass(element, BundleSerializer.class);
    validateSerializer(element, BundleSerializer.class, bundleSerializer, PocketKnifeBundleSerializer.class);

    // Assemble information on the bind point
    String name = element.getSimpleName().toString();
    String bundleType = null;
    KeySpec key = getKey(element);
    boolean canHaveDefault = false;
    boolean needsToBeCast = false;
    NotRequired notRequired = element.getAnnotation(NotRequired.class);
    boolean required = notRequired == null;
    int minSdk = Build.VERSION_CODES.FROYO;
    if (!required) {
        minSdk = notRequired.value();
    }
    if (bundleSerializer == null) {
        bundleType = typeUtil.getBundleType(type);
        canHaveDefault = !required && canHaveDefault(type, minSdk);
        needsToBeCast = typeUtil.needToCastBundleType(type);
    }

    BundleBindingAdapterGenerator bundleBindingAdapterGenerator = getOrCreateTargetClass(targetClassMap, enclosingElement);
    BundleFieldBinding binding = new BundleFieldBinding(BundleFieldBinding.AnnotationType.ARGUMENT, name, access, type, bundleType, key,
            needsToBeCast, canHaveDefault, required, bundleSerializer);
    bundleBindingAdapterGenerator.orRequired(required);
    bundleBindingAdapterGenerator.addField(binding);

    // Add the type-erased version to the valid targets set.
    erasedTargetNames.add(enclosingElement.toString());
}
 
源代码19 项目: butterknife   文件: ButterKnifeProcessor.java
private void parseBindViews(Element element, Map<TypeElement, BindingSet.Builder> builderMap,
    Set<TypeElement> erasedTargetNames) {
  TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();

  // Start by verifying common generated code restrictions.
  boolean hasError = isInaccessibleViaGeneratedCode(BindViews.class, "fields", element)
      || isBindingInWrongPackage(BindViews.class, element);

  // Verify that the type is a List or an array.
  TypeMirror elementType = element.asType();
  String erasedType = doubleErasure(elementType);
  TypeMirror viewType = null;
  FieldCollectionViewBinding.Kind kind = null;
  if (elementType.getKind() == TypeKind.ARRAY) {
    ArrayType arrayType = (ArrayType) elementType;
    viewType = arrayType.getComponentType();
    kind = FieldCollectionViewBinding.Kind.ARRAY;
  } else if (LIST_TYPE.equals(erasedType)) {
    DeclaredType declaredType = (DeclaredType) elementType;
    List<? extends TypeMirror> typeArguments = declaredType.getTypeArguments();
    if (typeArguments.size() != 1) {
      error(element, "@%s List must have a generic component. (%s.%s)",
          BindViews.class.getSimpleName(), enclosingElement.getQualifiedName(),
          element.getSimpleName());
      hasError = true;
    } else {
      viewType = typeArguments.get(0);
    }
    kind = FieldCollectionViewBinding.Kind.LIST;
  } else {
    error(element, "@%s must be a List or array. (%s.%s)", BindViews.class.getSimpleName(),
        enclosingElement.getQualifiedName(), element.getSimpleName());
    hasError = true;
  }
  if (viewType != null && viewType.getKind() == TypeKind.TYPEVAR) {
    TypeVariable typeVariable = (TypeVariable) viewType;
    viewType = typeVariable.getUpperBound();
  }

  // Verify that the target type extends from View.
  if (viewType != null && !isSubtypeOfType(viewType, VIEW_TYPE) && !isInterface(viewType)) {
    if (viewType.getKind() == TypeKind.ERROR) {
      note(element, "@%s List or array with unresolved type (%s) "
              + "must elsewhere be generated as a View or interface. (%s.%s)",
          BindViews.class.getSimpleName(), viewType, enclosingElement.getQualifiedName(),
          element.getSimpleName());
    } else {
      error(element, "@%s List or array type must extend from View or be an interface. (%s.%s)",
          BindViews.class.getSimpleName(), enclosingElement.getQualifiedName(),
          element.getSimpleName());
      hasError = true;
    }
  }

  // Assemble information on the field.
  String name = element.getSimpleName().toString();
  int[] ids = element.getAnnotation(BindViews.class).value();
  if (ids.length == 0) {
    error(element, "@%s must specify at least one ID. (%s.%s)", BindViews.class.getSimpleName(),
        enclosingElement.getQualifiedName(), element.getSimpleName());
    hasError = true;
  }

  Integer duplicateId = findDuplicate(ids);
  if (duplicateId != null) {
    error(element, "@%s annotation contains duplicate ID %d. (%s.%s)",
        BindViews.class.getSimpleName(), duplicateId, enclosingElement.getQualifiedName(),
        element.getSimpleName());
    hasError = true;
  }

  if (hasError) {
    return;
  }

  TypeName type = TypeName.get(requireNonNull(viewType));
  boolean required = isFieldRequired(element);

  BindingSet.Builder builder = getOrCreateBindingBuilder(builderMap, enclosingElement);
  builder.addFieldCollection(new FieldCollectionViewBinding(name, type, requireNonNull(kind),
      new ArrayList<>(elementToIds(element, BindViews.class, ids).values()), required));

  erasedTargetNames.add(enclosingElement);
}
 
源代码20 项目: netbeans   文件: ComparatorParameterNotUsed.java
@Hint(
    displayName = "#DN_ComparatorParameterNotUsed",
    description = "#DESC_ComparatorParameterNotUsed",
    category = "bugs",
    suppressWarnings = { "ComparatorMethodParameterNotUsed" },
    enabled = true
)
@TriggerPattern("public int compare($v1, $v2) { $stmts$; } ")
public static List<ErrorDescription> run(HintContext ctx) {
    CompilationInfo ci = ctx.getInfo();
    Element me = ci.getTrees().getElement(ctx.getPath());
    if (me == null) {
        return null;
    }
    Element clazz = me.getEnclosingElement();
    if (clazz == null || !(
            clazz.getKind().isClass() || 
        /* JDK8 */ (clazz.getKind().isInterface() && me.getModifiers().contains(Modifier.DEFAULT)))
    ) {
        // method bod not valid at this point
        return null;
    }
    TypeMirror tm = clazz.asType();
    TypeElement comparableIface = ci.getElements().getTypeElement("java.lang.Comparable"); // NOI18N
    // the eclosing type must implement or extend comparable
    if (comparableIface == null || 
        !ci.getTypes().isSubtype(tm, comparableIface.asType())) {
        return null;
    }
    Set<VariableElement> vars = new HashSet<VariableElement>(2);
    ExecutableElement ee  = (ExecutableElement)me;
    vars.addAll(ee.getParameters());

    ComparatorParameterNotUsed v = new ComparatorParameterNotUsed(ci, vars);
    MethodTree mt = (MethodTree)ctx.getPath().getLeaf();
    if (mt.getBody() == null) {
        return null;
    }
    try {
        v.scan(new TreePath(ctx.getPath(), mt.getBody()), v);
    } catch (StopProcessing ex) {
        // nothing, just fast interrupt
    }
    if (v.unusedVars.isEmpty()) {
        return null;
    }
    // the method has exactly 2 parameters:
    VariableTree par1 = mt.getParameters().get(0);
    VariableTree par2 = mt.getParameters().get(1);
    
    List<? extends VariableElement> ll = new ArrayList<VariableElement>(v.unusedVars);
    List<ErrorDescription> res = new ArrayList<>(ll.size());
    Collections.sort(ll, Collator.getInstance());
    for (VariableElement ve : ll) {
        Tree vt = ve.getSimpleName() == par1.getName() ? par1 : par2;
        res.add(
                ErrorDescriptionFactory.forName(ctx, vt, 
                    TEXT_ComparatorParameterNotUsed(ve.getSimpleName().toString())
        ));
    }
    return res;
}