Java 类javax.lang.model.element.VariableElement 实例源码

项目:incubator-netbeans    文件:GoToSupport.java   
private void dumpArguments(List<? extends VariableElement> list, List<? extends TypeMirror> types) {
    boolean addSpace = false;

    result.append('(');

    Iterator<? extends VariableElement> listIt = list.iterator();
    Iterator<? extends TypeMirror> typesIt = types != null ? types.iterator() : null;

    while (listIt.hasNext()) {
        if (addSpace) {
            result.append(", ");
        }

        VariableElement ve = listIt.next();
        TypeMirror      type = typesIt != null ? typesIt.next() : ve.asType();

        result.append(getTypeName(info, type, true));
        result.append(" ");
        result.append(ve.getSimpleName());

        addSpace = true;
    }

    result.append(')');
}
项目:incubator-netbeans    文件:GeneratorUtilities.java   
/**
 * Creates a setter method for a field.
 *
 * @param clazz the class to create the setter within
 * @param field field to create setter for
 * @return the setter method
 * @since 0.20
 */
public MethodTree createSetter(TypeElement clazz, VariableElement field) {
    assert clazz != null && field != null;
    TreeMaker make = copy.getTreeMaker();
    CodeStyle cs = DiffContext.getCodeStyle(copy);
    Set<Modifier> mods = EnumSet.of(Modifier.PUBLIC);
    boolean isStatic = field.getModifiers().contains(Modifier.STATIC);
    if (isStatic) {
        mods.add(Modifier.STATIC);
    }
    CharSequence name = field.getSimpleName();
    assert name.length() > 0;
    TypeMirror type = copy.getTypes().asMemberOf((DeclaredType)clazz.asType(), field);
    String setterName = CodeStyleUtils.computeSetterName(field.getSimpleName(), isStatic, cs);
    String paramName = addParamPrefixSuffix(removeFieldPrefixSuffix(field, cs), cs);
    List<VariableTree> params = Collections.singletonList(make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), paramName, make.Type(type), null));
    BlockTree body = make.Block(Collections.singletonList(make.ExpressionStatement(make.Assignment(make.MemberSelect(isStatic? make.Identifier(field.getEnclosingElement().getSimpleName()) : make.Identifier("this"), name), make.Identifier(paramName)))), false); //NOI18N
    return make.Method(make.Modifiers(mods), setterName, make.Type(copy.getTypes().getNoType(TypeKind.VOID)), Collections.<TypeParameterTree>emptyList(), params, Collections.<ExpressionTree>emptyList(), body, null);
}
项目:incubator-netbeans    文件:NPECheck.java   
@Override
public State visitVariable(VariableTree node, Void p) {
    Element e = info.getTrees().getElement(getCurrentPath());
    Map<VariableElement, State> orig = new HashMap<>(variable2State);
    State r = scan(node.getInitializer(), p);

    mergeHypotheticalVariable2State(orig);

    if (e != null) {
        variable2State.put((VariableElement) e, r);
        TreePath pp = getCurrentPath().getParentPath();
        if (pp != null) {
            addScopedVariable(pp.getLeaf(), (VariableElement)e);
        }
    }

    return r;
}
项目:incubator-netbeans    文件:GeneratorUtilitiesTest.java   
public void run(WorkingCopy copy) throws Exception {
    copy.toPhase(JavaSource.Phase.RESOLVED);
    TreePath tp = copy.getTreeUtilities().pathFor(offset);
    assertTrue(TreeUtilities.CLASS_TREE_KINDS.contains(tp.getLeaf().getKind()));
    ClassTree ct = (ClassTree)tp.getLeaf();
    TypeElement te = (TypeElement)copy.getTrees().getElement(tp);
    assertNotNull(te);
    List<? extends VariableElement> vars = ElementFilter.fieldsIn(te.getEnclosedElements());
    TypeElement sup = (TypeElement)((DeclaredType)te.getSuperclass()).asElement();
    assertNotNull(sup);
    List<? extends ExecutableElement> ctors = sup.getQualifiedName().contentEquals("java.lang.Object")
            ? null : ElementFilter.constructorsIn(sup.getEnclosedElements());
    if (ctors != null)
        assertEquals(numCtors, ctors.size());
    GeneratorUtilities utilities = GeneratorUtilities.get(copy);
    assertNotNull(utilities);
    ClassTree newCt = utilities.insertClassMember(ct, utilities.createConstructor(te, vars, ctors != null ? ctors.get(ctorToUse) : null));
    copy.rewrite(ct, newCt);
}
项目:incubator-netbeans    文件:JavadocHelper.java   
@NonNull
private static Collection<? extends CharSequence> getFragment(Element e) {
    final FragmentBuilder fb = new FragmentBuilder();
    if (!e.getKind().isClass() && !e.getKind().isInterface()) {
        if (e.getKind() == ElementKind.CONSTRUCTOR) {
            fb.append(e.getEnclosingElement().getSimpleName());
        } else {
            fb.append(e.getSimpleName());
        }
        if (e.getKind() == ElementKind.METHOD || e.getKind() == ElementKind.CONSTRUCTOR) {
            ExecutableElement ee = (ExecutableElement) e;
            fb.append("("); //NOI18N
            for (Iterator<? extends VariableElement> it = ee.getParameters().iterator(); it.hasNext();) {
                VariableElement param = it.next();
                appendType(fb, param.asType(), ee.isVarArgs() && !it.hasNext());
                if (it.hasNext()) {
                    fb.append(", ");    //NOI18N
                }
            }
            fb.append(")"); //NOI18N
        }
    }
    return fb.getFragments();
}
项目:react4j    文件:ReactProcessor.java   
private boolean isInjectionRequired( @Nonnull final TypeElement typeElement )
{
  final VariableElement injectParameter = (VariableElement)
    ProcessorUtil.getAnnotationValue( processingEnv.getElementUtils(),
                                      typeElement,
                                      Constants.REACT_COMPONENT_ANNOTATION_CLASSNAME,
                                      "inject" ).getValue();
  switch ( injectParameter.getSimpleName().toString() )
  {
    case "ENABLE":
      return true;
    case "DISABLE":
      return false;
    default:
      return ProcessorUtil.getFieldElements( typeElement ).stream().anyMatch( this::hasInjectAnnotation ) ||
             ProcessorUtil.getMethods( typeElement, processingEnv.getTypeUtils() ).
               stream().anyMatch( this::hasInjectAnnotation );
  }
}
项目:GitHub    文件:RequestOptionsGenerator.java   
private MethodSpec generateRequestOptionOverride(ExecutableElement methodToOverride) {
  return MethodSpec.overriding(methodToOverride)
      .returns(glideOptionsName)
      .addCode(CodeBlock.builder()
          .add("return ($T) super.$N(", glideOptionsName, methodToOverride.getSimpleName())
          .add(FluentIterable.from(methodToOverride.getParameters())
              .transform(new Function<VariableElement, String>() {
                @Override
                public String apply(VariableElement input) {
                  return input.getSimpleName().toString();
                }
              })
              .join(Joiner.on(", ")))
          .add(");\n")
          .build())
      .build();
}
项目:incubator-netbeans    文件:AbstractTestGenerator.java   
/**
 * Checks whether the interface declare given method
 *
 * @param trgInterface interface to be declaring the method
 * @param srcMethod method to be declared
 * @return {@code true} if the method is declared by the interface, {@code false} otherwise
 */
private static boolean isMethodDeclaredByInterface(TypeElement trgInterface, ExecutableElement srcMethod) {
    List<? extends Element> enclosedElements = trgInterface.getEnclosedElements();
    List<? extends VariableElement> methodParameters = srcMethod.getParameters();
    for (Element enclosedElement : enclosedElements) {
        if (enclosedElement instanceof ExecutableElement) {
            ExecutableElement exElement = (ExecutableElement) enclosedElement;
            List<? extends VariableElement> elementParameters = exElement.getParameters();
            if (srcMethod.getSimpleName() != exElement.getSimpleName()
                    || (methodParameters.size() != elementParameters.size())) {
                continue;
            }
            for (int i = 0; i < methodParameters.size(); i++) {
                if (!((VariableElement) methodParameters.get(i)).asType().toString().equals(
                        ((VariableElement) elementParameters.get(i)).asType().toString())) {
                    continue;
                }
            }
            return true;
        }
    }
    return false;
}
项目:GitHub    文件:RealmProxyClassGenerator.java   
private void emitPersistedFieldAccessors(final JavaWriter writer) throws IOException {
    for (final VariableElement field : metadata.getFields()) {
        final String fieldName = field.getSimpleName().toString();
        final String fieldTypeCanonicalName = field.asType().toString();

        if (Constants.JAVA_TO_REALM_TYPES.containsKey(fieldTypeCanonicalName)) {
            emitPrimitiveType(writer, field, fieldName, fieldTypeCanonicalName);
        } else if (Utils.isMutableRealmInteger(field)) {
            emitMutableRealmInteger(writer, field, fieldName, fieldTypeCanonicalName);
        } else if (Utils.isRealmModel(field)) {
            emitRealmModel(writer, field, fieldName, fieldTypeCanonicalName);
        } else if (Utils.isRealmList(field)) {
            final TypeMirror elementTypeMirror = TypeMirrors.getRealmListElementTypeMirror(field);
            emitRealmList(writer, field, fieldName, fieldTypeCanonicalName, elementTypeMirror);
        } else {
            throw new UnsupportedOperationException(String.format(Locale.US,
                    "Field \"%s\" of type \"%s\" is not supported.", fieldName, fieldTypeCanonicalName));
        }

        writer.emitEmptyLine();
    }
}
项目:incubator-netbeans    文件:GeneratorUtils.java   
public static void generateGettersAndSetters(WorkingCopy wc, TreePath path, Iterable<? extends VariableElement> fields, int type, int offset) {
    assert TreeUtilities.CLASS_TREE_KINDS.contains(path.getLeaf().getKind());
    TypeElement te = (TypeElement)wc.getTrees().getElement(path);
    if (te != null) {
        GeneratorUtilities gu = GeneratorUtilities.get(wc);
        ClassTree clazz = (ClassTree)path.getLeaf();
        List<Tree> members = new ArrayList<>();
        for(VariableElement element : fields) {
            if (type != SETTERS_ONLY) {
                members.add(gu.createGetter(te, element));
            }
            if (type != GETTERS_ONLY) {
                members.add(gu.createSetter(te, element));
            }
        }
        wc.rewrite(clazz, insertClassMembers(wc, clazz, members, offset));
    }
}
项目:RapidRouter    文件:ElementUtil.java   
/**
 * 两组参数类型相同
 */
public static boolean deepSame(List<? extends VariableElement> _this, List<? extends VariableElement> _that) {
    if (null == _this && null == _that) {
        return true;
    }

    if (null == _this || null == _that) {
        return false;
    }

    if (_this.size() != _that.size()) {
        return false;
    }

    for (int i = 0, len = _this.size(); i < len; i++) {
        VariableElement _thisEle = _this.get(i);
        VariableElement _thatEle = _that.get(i);

        if (!MoreElements.asType(_thisEle).getQualifiedName().toString()
                .equals(MoreElements.asType(_thatEle).getQualifiedName().toString())) {
            return false;
        }
    }

    return true;
}
项目:OpenJSharp    文件:PubapiVisitor.java   
/**
 * Creates a String representation of a variable element with everything
 * necessary to track all public aspects of it in an API.
 * @param e Element to create String for.
 * @return String representation of element.
 */
protected String makeVariableString(VariableElement e) {
    StringBuilder result = new StringBuilder();
    for (Modifier modifier : e.getModifiers()) {
        result.append(modifier.toString());
        result.append(" ");
    }
    result.append(e.asType().toString());
    result.append(" ");
    result.append(e.toString());
    Object value = e.getConstantValue();
    if (value != null) {
        result.append(" = ");
        if (e.asType().toString().equals("char")) {
            int v = (int)value.toString().charAt(0);
            result.append("'\\u"+Integer.toString(v,16)+"'");
        } else {
            result.append(value.toString());
        }
    }
    return result.toString();
}
项目:incubator-netbeans    文件:JPAEditorUtil.java   
public static VariableElement findFieldElementOnType(ElementUtilities eu, TypeMirror type, String fieldName) {
    FieldAcceptor fieldAcceptor = new FieldAcceptor(fieldName);
    Iterable<? extends Element> matchingProp = eu.getMembers(type, fieldAcceptor);
    Iterator<? extends Element> it = matchingProp.iterator();

    // no matching element found
    if (!it.hasNext()) {
        return null;
    } else
        return (VariableElement)it.next();

}
项目:openjdk-jdk10    文件:AbstractExecutableMemberWriter.java   
/**
 * Add the parameter for the executable member.
 *
 * @param member the member to write parameter for.
 * @param param the parameter that needs to be written.
 * @param isVarArg true if this is a link to var arg.
 * @param tree the content tree to which the parameter information will be added.
 */
protected void addParam(ExecutableElement member, VariableElement param,
        boolean isVarArg, Content tree) {
    Content link = writer.getLink(new LinkInfoImpl(configuration, EXECUTABLE_MEMBER_PARAM,
            param.asType()).varargs(isVarArg));
    tree.addContent(link);
    if(name(param).length() > 0) {
        tree.addContent(Contents.SPACE);
        tree.addContent(name(param));
    }
}
项目:openjdk-jdk10    文件:NodeIntrinsicVerifier.java   
private List<ExecutableElement> findIntrinsifyFactoryMethod(TypeElement nodeClass, TypeMirror[] signature, Map<ExecutableElement, String> nonMatches, boolean requiresInjectedStamp) {
    List<ExecutableElement> methods = ElementFilter.methodsIn(nodeClass.getEnclosedElements());
    List<ExecutableElement> found = new ArrayList<>(methods.size());
    for (ExecutableElement method : methods) {
        if (!method.getSimpleName().toString().equals("intrinsify")) {
            continue;
        }

        if (method.getParameters().size() < 2) {
            continue;
        }

        VariableElement firstArg = method.getParameters().get(0);
        if (!isTypeCompatible(firstArg.asType(), graphBuilderContextType())) {
            continue;
        }

        VariableElement secondArg = method.getParameters().get(1);
        if (!isTypeCompatible(secondArg.asType(), resolvedJavaMethodType())) {
            continue;
        }

        if (method.getReturnType().getKind() != TypeKind.BOOLEAN) {
            continue;
        }

        if (matchSignature(2, method, signature, nonMatches, requiresInjectedStamp)) {
            found.add(method);
        }
    }
    return found;
}
项目:openjdk-jdk10    文件:T8136453.java   
void run() {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    List<String> opts = Arrays.asList("-parameters");
    JavacTask task = (JavacTask) compiler.getTask(null, null, null, opts, null, null);
    TypeElement t = task.getElements().getTypeElement("T");
    ExecutableElement testMethod = ElementFilter.methodsIn(t.getEnclosedElements()).get(0);
    VariableElement param = testMethod.getParameters().get(0);
    Name paramName = param.getSimpleName();

    if (!paramName.contentEquals("p")) {
        throw new AssertionError("Wrong parameter name: " + paramName);
    }
}
项目:openjdk-jdk10    文件:Utils.java   
/**
 * @param e1 the first method to compare.
 * @param e2 the second method to compare.
 * @return true if member1 overrides/hides or is overriden/hidden by member2.
 */

public boolean executableMembersEqual(ExecutableElement e1, ExecutableElement e2) {
    // TODO: investigate if Elements.hides(..) will work here.
    if (isStatic(e1) && isStatic(e2)) {
        List<? extends VariableElement> parameters1 = e1.getParameters();
        List<? extends VariableElement> parameters2 = e2.getParameters();
        if (e1.getSimpleName().equals(e2.getSimpleName()) &&
                parameters1.size() == parameters2.size()) {
            int j;
            for (j = 0 ; j < parameters1.size(); j++) {
                VariableElement v1 = parameters1.get(j);
                VariableElement v2 = parameters2.get(j);
                String t1 = getTypeName(v1.asType(), true);
                String t2 = getTypeName(v2.asType(), true);
                if (!(t1.equals(t2) ||
                        isTypeVariable(v1.asType()) || isTypeVariable(v2.asType()))) {
                    break;
                }
            }
            if (j == parameters1.size()) {
            return true;
            }
        }
        return false;
    } else {
        return elementUtils.overrides(e1, e2, getEnclosingTypeElement(e1)) ||
                elementUtils.overrides(e2, e1, getEnclosingTypeElement(e2)) ||
                e1.equals(e2);
    }
}
项目:auto-adapter    文件:Predicates.java   
static Predicate<? super ExecutableElement> parameterIsSameType(final TypeElement model) {
    return new MyPredicate<ExecutableElement>() {
        @Override
        public boolean test(final ExecutableElement input) {
            VariableElement variableElement = input.getParameters().get(0);

            String modelAsString = Util.typeToString(model.asType());
            String paramAsString = Util.typeToString(variableElement.asType());
            return modelAsString.equals(paramAsString);
        }
    };
}
项目:incubator-netbeans    文件:NPECheck.java   
private Map<VariableElement, State> findStateDifference(Map<VariableElement, State> basepoint) {
    Map<VariableElement, State> m = new HashMap<>();
    for (Map.Entry<VariableElement, State> vEntry : variable2State.entrySet()) {
        VariableElement k = vEntry.getKey();
        State s = basepoint.get(k);
        if (s != vEntry.getValue()) {
            m.put(k, vEntry.getValue());
        }
    }
    return m;
}
项目:Spyglass    文件:TestGetPlaceholderMethodGenerator.java   
@Test
public void testGenerateFor_parameterWithUseString() {
    final VariableElement parameter = avatarRule.getElementWithUniqueId("string");
    final AnnotationMirror useAnnotation = UseAnnoRetriever.getAnnotation(parameter);

    final MethodSpec generatedMethod = generator.generateFor(useAnnotation, 0);

    checkSignature(generatedMethod, ClassName.get(String.class));
    checkCompiles(generatedMethod);
}
项目:Spyglass    文件:TestUseAnnotationRetriever.java   
@Test
public void testGetAnnotation_useDoubleAnnotationPresent() {
    final VariableElement element = avatarRule.getElementWithUniqueId("double");

    final AnnotationMirror mirror = UseAnnoRetriever.getAnnotation(element);

    assertThat(mirror, is(notNullValue()));
    assertThat(mirror.getAnnotationType().toString(), is(UseDouble.class.getName()));
}
项目:annotation-processor-toolkit    文件:ElementUtils_AccessEnclosingElementsTest.java   
@Test
public void getFirstEnclosingElementOfKind_validUsageWithNoHit() {

    // Prepare
    Element parameterElement = Mockito.mock(VariableElement.class);
    Element methodElement = Mockito.mock(ExecutableElement.class);
    Element embeddedTypeElement = Mockito.mock(TypeElement.class);
    Element typeElement = Mockito.mock(TypeElement.class);
    Element packageElement = Mockito.mock(PackageElement.class);

    Mockito.when(parameterElement.getKind()).thenReturn(ElementKind.PARAMETER);
    Mockito.when(methodElement.getKind()).thenReturn(ElementKind.METHOD);
    Mockito.when(embeddedTypeElement.getKind()).thenReturn(ElementKind.CLASS);
    Mockito.when(typeElement.getKind()).thenReturn(ElementKind.CLASS);
    Mockito.when(packageElement.getKind()).thenReturn(ElementKind.PACKAGE);


    Mockito.when(parameterElement.getEnclosingElement()).thenReturn(methodElement);
    Mockito.when(methodElement.getEnclosingElement()).thenReturn(embeddedTypeElement);
    Mockito.when(embeddedTypeElement.getEnclosingElement()).thenReturn(typeElement);
    Mockito.when(typeElement.getEnclosingElement()).thenReturn(packageElement);

    // execute
    Element result = ElementUtils.AccessEnclosingElements.getFirstEnclosingElementOfKind(parameterElement, ElementKind.CONSTRUCTOR);

    // validate
    MatcherAssert.assertThat(result, Matchers.nullValue());


}
项目:AptSpring    文件:SpringAnnotationParser.java   
/**
 * Builds an instance model by finding the autowired constructor of an @Component model as well as 
 * 
 * @param te the TypeElement corresponding to the @Component class.
 * @param dm the definitionModel built from the @Component.
 * @param names the list if names in an @Component annotation.  Users must explicitly define one.
 * @param messager errors are added to this APT messager.
 */
private void addModelsFromComponent(TypeElement te, DefinitionModel dm, String[] names, Messager messager) {
  List<InstanceDependencyModel> dependencies = new ArrayList<>();
  ExecutableElement chosenConstructor = findAutowiredConstructor(extractConstructorsFromComponent(te));
  if (chosenConstructor == null) {
    messager.printMessage(Kind.ERROR, "No single default constructor or single @Autowired constructor", te);
  } else {
    dependencies = execElementDependency(messager, dm, chosenConstructor);
    //dm.getExpectedDefinitions()
  }
  te.getEnclosedElements().stream()
      .filter(el -> el instanceof VariableElement)
      .map(el -> (VariableElement) el)
      .filter(ve -> !staticPrivateFinalLiteralField.test(ve) && !privateFinalField.test(ve))
      .forEach(ve -> messager
          .printMessage(Kind.ERROR, "@Component classes my only have static final constant fields or final private fields", ve));

  InstanceModel model = new InstanceModel(names[0],
      dm.getIdentity(), 
      chosenConstructor, 
      te.getQualifiedName().toString(),
      dependencies, 
      new ArrayList<>());

  dm.addDefinition(model);
  for (InstanceDependencyModel dep : dependencies) {
    ExpectedModel expectedModel = new ExpectedModel(dep.getIdentity());
    expectedModel.addDefinitionReferenceToType(model.getIdentity(), dep.getType());
    dm.addDefinition(expectedModel);
  }
}
项目:openjdk-jdk10    文件:PubapiVisitor.java   
@Override @DefinedBy(Api.LANGUAGE_MODEL)
public Void visitVariable(VariableElement e, Void p) {
    if (isNonPrivate(e)) {
        Object constVal = e.getConstantValue();
        String constValStr = null;
        // TODO: This doesn't seem to be entirely accurate. What if I change
        // from, say, 0 to 0L? (And the field is public final static so that
        // it could get inlined.)
        if (constVal != null) {
            if (e.asType().toString().equals("char")) {
                // What type is 'value'? Is it already a char?
                char c = constVal.toString().charAt(0);
                constValStr = "'" + encodeChar(c) + "'";
            } else {
                constValStr = constVal.toString()
                                      .chars()
                                      .mapToObj(PubapiVisitor::encodeChar)
                                      .collect(Collectors.joining("", "\"", "\""));
            }
        }

        PubVar v = new PubVar(e.getModifiers(),
                              TypeDesc.fromType(e.asType()),
                              e.toString(),
                              constValStr);
        collectedApi.variables.put(v.identifier, v);
    }

    // Safe to not recurse here, because the only thing
    // to visit here is the constructor of a variable declaration.
    // If it happens to contain an anonymous inner class (which it might)
    // then this class is never visible outside of the package anyway, so
    // we are allowed to ignore it here.
    return null;
}
项目:incubator-netbeans    文件:AnnotationParser.java   
public Object getValue(AnnotationValue elementValue) {
    Object value = elementValue.getValue();
    if (value instanceof VariableElement) {
        VariableElement field = (VariableElement)value;
        TypeMirror enumType = field.getEnclosingElement().asType();
        if (isSameAsTypeToCheck(enumType)) {
            return field.getSimpleName().toString();
        }
    }
    return getDefaultValue();
}
项目:RxAndroidOrm    文件:ProcessUtils.java   
public static Element getIdField(Element element) {
    for (VariableElement e : getFields(element)) {
        if (isIdField(e)) {
            return e;
        }
    }
    return null;
}
项目:D-Router    文件:RouterProcessor.java   
public void parseParams(Element element) {
    if (isPrivate(element)) {
        printError(element, "%s can't be private", element.getSimpleName());
        return;
    }
    VariableElement variableElement = (VariableElement) element;
    Param param = element.getAnnotation(Param.class);
    FieldInfo info = new FieldInfo(variableElement.getSimpleName().toString(), param.value(), convertClass(element.asType().toString()));
    ActivityInfo activityInfo = findActivityInfo(element);
    activityInfo.addParam(info);
}
项目:GitHub    文件:GlideExtensionValidator.java   
private static void validateExtendsRequestOptions(ExecutableElement executableElement) {
  validateStaticVoid(executableElement, GlideOption.class);
  if (executableElement.getParameters().isEmpty()) {
    throw new IllegalArgumentException("@GlideOption methods must take a "
        + "RequestOptions object as their first parameter, but given none");
  }
  VariableElement first = executableElement.getParameters().get(0);
  TypeMirror expected = first.asType();
  if (!expected.toString().equals(
      "com.bumptech.glide.request.RequestOptions")) {
    throw new IllegalArgumentException("@GlideOption methods must take a"
        + " RequestOptions object as their first parameter, but given: " + expected);
  }
}
项目:AnnotationProcessorStarter    文件:GeneratedMethod.java   
private MethodSpec.Builder buildSignature() {
    final MethodSpec.Builder lBuilder = MethodSpec.methodBuilder(mMethodElement.getSimpleName().toString())
            .addModifiers(Modifier.PUBLIC, Modifier.STATIC);

    if (!mIsStaticMethod) {
        lBuilder.addParameter(ParameterSpec.builder(ClassName.get(mClassElement), "instance").build());
    }

    for (final VariableElement lParamElement : mMethodElement.getParameters()) {
        lBuilder.addParameter(ParameterSpec.get(lParamElement));
    }

    return lBuilder;
}
项目:incubator-netbeans    文件:ReplaceBufferByString.java   
@TriggerPatterns({
    @TriggerPattern(value = "java.lang.StringBuffer $x = $expr;"),
    @TriggerPattern(value = "java.lang.StringBuilder $x = $expr;"),
})
public static ErrorDescription checkReplace(HintContext ctx) {
    CompilationInfo ci = ctx.getInfo();
    TreePath vp = ctx.getVariables().get("$x"); // NOI18N
    TreePath initP = ctx.getVariables().get("$expr"); // NOI18N
    Element el = ci.getTrees().getElement(vp);
    if (el == null || el.getKind() != ElementKind.LOCAL_VARIABLE) {
        return null;
    }

    StringBufferUsageScanner scanner = new StringBufferUsageScanner(ci, ((VariableElement)el));
    TreePath declRoot = ctx.getPath().getParentPath();
    scanner.scan(declRoot, null);
    if (scanner.isIncompatible()) {
        return null;
    }
    NewAppendScanner newScan = new NewAppendScanner(ci);
    if (newScan.scan(initP, null) != Boolean.TRUE || !newScan.hasContents) {
        return null;
    }

    return ErrorDescriptionFactory.forTree(ctx, ctx.getPath(), Bundle.TEXT_ReplaceStringBufferByString(), 
            new RewriteToStringFix(
                TreePathHandle.create(vp, ci),
                TreePathHandle.create(declRoot, ci)
            ).toEditorFix());
}
项目:Java-9-Programming-By-Example    文件:Aptools.java   
/**
 * Get an array of lists containing the annotations of the arguments.
 */
@Transition(from = "MethodTool", end = true)
public List<? extends AnnotationMirror>[] getParameterAnnotations() {
  @SuppressWarnings("unchecked")
  List<? extends AnnotationMirror>[] annotationMirrorss = new List[getTheNumberOfParameters()];
  int i = 0;
  for (VariableElement parameterElement : methodElement.getParameters()) {
    annotationMirrorss[i] = parameterElement.getAnnotationMirrors();
    i++;
  }
  return annotationMirrorss;
}
项目:OpenJSharp    文件:ApNavigator.java   
public VariableElement[] getEnumConstants(TypeElement clazz) {
    List<? extends Element> elements = env.getElementUtils().getAllMembers(clazz);
    Collection<VariableElement> constants = new HashSet<VariableElement>();
    for (Element element : elements) {
        if (element.getKind().equals(ElementKind.ENUM_CONSTANT)) {
            constants.add((VariableElement) element);
        }
    }
    return constants.toArray(new VariableElement[constants.size()]);
}
项目:incubator-netbeans    文件:JpaControllerUtil.java   
public static VariableElement guessField(ExecutableElement getter) {
    String name = getter.getSimpleName().toString().substring(3);
    String guessFieldName = name.substring(0,1).toLowerCase() + name.substring(1);
    TypeElement typeElement = (TypeElement) getter.getEnclosingElement();
    for (VariableElement variableElement : ElementFilter.fieldsIn(typeElement.getEnclosedElements())) {
        if (variableElement.getSimpleName().contentEquals(guessFieldName)) {
            return variableElement;
        }
    }
    Logger.getLogger(JpaControllerUtil.class.getName()).log(Level.WARNING, "Cannot detect the field associated with property: {0}", guessFieldName);
    return null;
}
项目:remoter    文件:ShortParamBuilder.java   
@Override
public void writeParamsToStub(VariableElement param, ParamType paramType, String paramName, MethodSpec.Builder methodBuilder) {
    super.writeParamsToStub(param, paramType, paramName, methodBuilder);
    if (param.asType().getKind() == TypeKind.ARRAY) {
        logError("short[] not supported, use int[]" + param.getSimpleName());
    } else {
        methodBuilder.addStatement(paramName + " = (short)data.readInt()");
    }
}
项目:openjdk-jdk10    文件:HtmlDocletWriter.java   
/**
 * Check whether there are any tags for Serialization Overview
 * section to be printed.
 *
 * @param field the VariableElement object to check for tags.
 * @return true if there are tags to be printed else return false.
 */
protected boolean hasSerializationOverviewTags(VariableElement field) {
    Content output = new ContentBuilder();
    TagletWriter.genTagOutput(configuration.tagletManager, field,
            configuration.tagletManager.getCustomTaglets(field),
            getTagletWriterInstance(false), output);
    return !output.isEmpty();
}
项目:remoter    文件:FloatParamBuilder.java   
@Override
public void writeParamsToStub(VariableElement param, ParamType paramType, String paramName, MethodSpec.Builder methodBuilder) {
    super.writeParamsToStub(param, paramType, paramName, methodBuilder);
    if (param.asType().getKind() == TypeKind.ARRAY) {
        if (paramType == ParamType.OUT) {
            writeOutParamsToStub(param, paramType, paramName, methodBuilder);
        } else {
            methodBuilder.addStatement(paramName + " = data.createFloatArray()");
        }
    } else {
        methodBuilder.addStatement(paramName + " = data.readFloat()");
    }
}
项目:incubator-netbeans    文件:ElementUtilities.java   
@Override
public StringBuilder visitVariable(VariableElement e, Boolean p) {
    if (p != Boolean.TRUE || e.getEnclosingElement() == null) {
        return DEFAULT_VALUE.append(e.getSimpleName());
    } else {
        return e.getEnclosingElement().accept(this, p).
            append(".").
            append(e.getSimpleName());
    }
}
项目:GitHub    文件:GlideExtensionValidator.java   
private static List<String> getComparableParameterNames(
    ExecutableElement element, boolean skipFirst) {
  List<? extends VariableElement> parameters = element.getParameters();
  if (skipFirst) {
    parameters = parameters.subList(1, parameters.size());
  }
  List<String> result = new ArrayList<>(parameters.size());
  for (VariableElement parameter : parameters) {
    result.add(parameter.asType().toString());
  }
  return result;
}
项目:DDComponentForAndroid    文件:MethodInfo.java   
public List<String> getMethodParametersSimple() {
    List<String> params = new ArrayList<>();
    for (VariableElement methodParameter : methodParameters) {
        params.add(methodParameter.getSimpleName().toString());
    }
    return params;
}
项目:Java-9-Programming-By-Example    文件:Aptools.java   
/**
 * Get an argument name that can be used as the {@code i}-th argument.
 * 
 * @param i
 *          zero based index of the argument
 * @return
 */
@Transition(from = "MethodTool", end = true)
public String getArgumentName(int i) {
  if (argumentNames == null) {
    argumentNames = new String[getTheNumberOfParameters()];
    int j = 0;
    for (VariableElement parameterElement : methodElement.getParameters()) {
      argumentNames[j] = parameterElement.getSimpleName().toString();
      j++;
    }
  }
  return argumentNames[i];
}