Java Code Examples for javax.lang.model.element.Element#asType()

The following examples show how to use javax.lang.model.element.Element#asType() . 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: FitProcessor.java    From fit with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 2
Source File: BaseProcessor.java    From pocketknife with Apache License 2.0 6 votes vote down vote up
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()));
}
 
Example 3
Source File: ABTestProcessor.java    From abtestgen with Apache License 2.0 6 votes vote down vote up
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);
    }
  }
}
 
Example 4
Source File: FitProcessor.java    From fit with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 5
Source File: ModelProperty.java    From kripton with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example 6
Source File: KratosProcessor.java    From Kratos with GNU Lesser General Public License v3.0 5 votes vote down vote up
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());
}
 
Example 7
Source File: AutoLayoutProcessor.java    From AutoLayout-Android with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 8
Source File: TypeUtils.java    From jackdaw with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 9
Source File: JDIWrappersTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 10
Source File: RouterProcessor.java    From YCApt with Apache License 2.0 5 votes vote down vote up
/**-----------------------------------------注解----------------------------------------*/

    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);
    }
 
Example 11
Source File: ParameterInjectionPointLogic.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 12
Source File: TypeUtils.java    From Witch-Android with Apache License 2.0 5 votes vote down vote up
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 "";
}
 
Example 13
Source File: InstanceRefFinder.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 14
Source File: OnActivityResultProcessor.java    From OnActivityResult with Apache License 2.0 4 votes vote down vote up
@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);
        }
    }
}
 
Example 15
Source File: ButterKnifeProcessor.java    From butterknife with Apache License 2.0 4 votes vote down vote up
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);
}
 
Example 16
Source File: RouterProcessor.java    From DDComponentForAndroid with Apache License 2.0 4 votes vote down vote up
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");
            }
        }
    }
 
Example 17
Source File: ELTypeUtilities.java    From netbeans with Apache License 2.0 4 votes vote down vote up
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();
}
 
Example 18
Source File: BundleBindingProcessor.java    From pocketknife with Apache License 2.0 4 votes vote down vote up
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());
}
 
Example 19
Source File: ButterKnifeProcessor.java    From butterknife with Apache License 2.0 4 votes vote down vote up
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);
}
 
Example 20
Source File: ComparatorParameterNotUsed.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@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;
}