@Before public void before() { mockedDataClassBuilderAnnotation = mock(DataClassBuilder.class); mockedProcessingEnv = mock(ProcessingEnvironment.class); mockedTypeElement = mock(TypeElement.class); when(mockedDataClassBuilderAnnotation.name()).thenReturn(""); when(mockedTypeElement.getAnnotation(DataClassBuilder.class)).thenReturn(mockedDataClassBuilderAnnotation); mockedElementUtils = mock(Elements.class); when(mockedProcessingEnv.getElementUtils()).thenReturn(mockedElementUtils); PackageElement mockedPackageElement = mock(PackageElement.class); when(mockedElementUtils.getPackageOf(any(Element.class))).thenReturn(mockedPackageElement); Name mockedQualifiedName = mock(Name.class); when(mockedPackageElement.getQualifiedName()).thenReturn(mockedQualifiedName); when(mockedQualifiedName.toString()).thenReturn("eu.rsulkowski.test"); dataClassBuilderDescriptor = new DataClassBuilderDescriptor(mockedProcessingEnv, mockedTypeElement); }
private void createOrUpdateFieldHolder(Element element, Elements elements, Types types, JsonObjectHolder objectHolder) { JsonIgnore ignoreAnnotation = element.getAnnotation(JsonIgnore.class); boolean shouldParse = ignoreAnnotation == null || ignoreAnnotation.ignorePolicy() == IgnorePolicy.SERIALIZE_ONLY; boolean shouldSerialize = ignoreAnnotation == null || ignoreAnnotation.ignorePolicy() == IgnorePolicy.PARSE_ONLY; if (shouldParse || shouldSerialize) { JsonFieldHolder fieldHolder = objectHolder.fieldMap.get(element.getSimpleName().toString()); if (fieldHolder == null) { fieldHolder = new JsonFieldHolder(); objectHolder.fieldMap.put(element.getSimpleName().toString(), fieldHolder); } String error = fieldHolder.fill(element, elements, types, null, null, objectHolder, shouldParse, shouldSerialize); if (!TextUtils.isEmpty(error)) { error(element, error); } } }
private void determineLifecycleMethods( @Nonnull final TypeElement typeElement, @Nonnull final ComponentDescriptor descriptor ) { /* * Get the list of lifecycle methods that have been overridden by typeElement * a parent class, or by a default method method implemented by typeElement or * a parent class. */ final Collection<ExecutableElement> lifecycleMethods = getComponentLifecycleMethods().values(); final Elements elementUtils = processingEnv.getElementUtils(); final Types typeUtils = processingEnv.getTypeUtils(); final TypeElement componentType = elementUtils.getTypeElement( Constants.COMPONENT_CLASSNAME ); final List<MethodDescriptor> overriddenLifecycleMethods = // Get all methods on type parent classes, and default methods from interfaces ProcessorUtil.getMethods( typeElement, processingEnv.getTypeUtils() ).stream() // Only keep methods that override the lifecycle methods .filter( m -> lifecycleMethods.stream().anyMatch( l -> elementUtils.overrides( m, l, typeElement ) ) ) //Remove those that come from the base classes .filter( m -> m.getEnclosingElement() != componentType ) .map( m -> new MethodDescriptor( m, (ExecutableType) typeUtils.asMemberOf( descriptor.getDeclaredType(), m ) ) ) .collect( Collectors.toList() ); descriptor.setLifecycleMethods( overriddenLifecycleMethods ); }
@Test public void testImplementsInterface() throws Exception { Elements mockElementUtils = Mockito.mock(Elements.class); Types mockTypeUtils = Mockito.mock(Types.class); TypeElement mockElement = Mockito.mock(TypeElement.class); doReturn(mockElement) .when(mockElementUtils) .getTypeElement(TestInterface.class.getName()); TypeMirror mockMirror = Mockito.mock(TypeMirror.class); doReturn(mockMirror) .when(mockElement) .asType(); doReturn(true) .when(mockTypeUtils) .isAssignable(mockMirror, mockMirror); boolean actual = Utils.implementsInterface(mockElementUtils, mockTypeUtils, mockElement, TestInterface.class); Assert.assertTrue(actual); }
private boolean isJsonFieldFieldAnnotationValid(Element element, Elements elements) { TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); Annotation objectAnnotation = enclosingElement.getAnnotation(JsonObject.class); if (objectAnnotation == null) { error(enclosingElement, "%s: @%s fields can only be in classes annotated with @%s.", enclosingElement.getQualifiedName(), JsonField.class.getSimpleName(), JsonObject.class.getSimpleName()); return false; } if (element.getModifiers().contains(PRIVATE) && (TextUtils.isEmpty(JsonFieldHolder.getGetter(element, elements)) || TextUtils.isEmpty(JsonFieldHolder.getSetter(element, elements)))) { error(element, "@%s annotation can only be used on private fields if both getter and setter are present.", JsonField.class.getSimpleName()); return false; } return true; }
public static Type typeFor(TypeMirror typeMirror, TypeMirror typeConverterType, Elements elements, Types types) { TypeMirror genericClassTypeMirror = types.erasure(typeMirror); boolean hasTypeConverter = typeConverterType != null && !typeConverterType.toString().equals("void"); Type type; if (!hasTypeConverter && typeMirror instanceof ArrayType) { TypeMirror arrayTypeMirror = ((ArrayType)typeMirror).getComponentType(); type = new ArrayCollectionType(Type.typeFor(arrayTypeMirror, null, elements, types)); } else if (!hasTypeConverter && !genericClassTypeMirror.toString().equals(typeMirror.toString())) { type = CollectionType.collectionTypeFor(typeMirror, genericClassTypeMirror, elements, types); if (type == null) { if (typeMirror.toString().contains("?")) { throw new RuntimeException("Generic types with wildcards are currently not supported by LoganSquare."); } try { type = new ParameterizedTypeField(TypeName.get(typeMirror)); } catch (Exception ignored) { } } } else { type = FieldType.fieldTypeFor(typeMirror, typeConverterType, elements, types); } return type; }
TypeMirrors(ProcessingEnvironment env) { final Types typeUtils = env.getTypeUtils(); final Elements elementUtils = env.getElementUtils(); STRING_MIRROR = elementUtils.getTypeElement("java.lang.String").asType(); BINARY_MIRROR = typeUtils.getArrayType(typeUtils.getPrimitiveType(TypeKind.BYTE)); BOOLEAN_MIRROR = elementUtils.getTypeElement(Boolean.class.getName()).asType(); LONG_MIRROR = elementUtils.getTypeElement(Long.class.getName()).asType(); INTEGER_MIRROR = elementUtils.getTypeElement(Integer.class.getName()).asType(); SHORT_MIRROR = elementUtils.getTypeElement(Short.class.getName()).asType(); BYTE_MIRROR = elementUtils.getTypeElement(Byte.class.getName()).asType(); DOUBLE_MIRROR = elementUtils.getTypeElement(Double.class.getName()).asType(); FLOAT_MIRROR = elementUtils.getTypeElement(Float.class.getName()).asType(); DATE_MIRROR = elementUtils.getTypeElement(Date.class.getName()).asType(); PRIMITIVE_LONG_MIRROR = typeUtils.getPrimitiveType(TypeKind.LONG); PRIMITIVE_INT_MIRROR = typeUtils.getPrimitiveType(TypeKind.INT); PRIMITIVE_SHORT_MIRROR = typeUtils.getPrimitiveType(TypeKind.SHORT); PRIMITIVE_BYTE_MIRROR = typeUtils.getPrimitiveType(TypeKind.BYTE); }
@Before public void init() { Messager messenger = mock(Messager.class); this.annotationValue = mock(AnnotationValue.class); this.annotationTypeMirror = mock(TypeMirror.class); this.executableElement = mock(ExecutableElement.class); this.annotationElement = mock(TypeElement.class); when(this.annotationElement.asType()).thenReturn(this.annotationTypeMirror); this.elementUtils = mock(Elements.class); when(this.elementUtils.getTypeElement(any())).thenReturn(this.annotationElement); this.processingEnv = mock(ProcessingEnvironment.class); when(processingEnv.getMessager()).thenReturn(messenger); when(processingEnv.getElementUtils()).thenReturn(this.elementUtils); // finally.... this.testee = new TSModuleHandler(processingEnv); }
public KickbackElementClass(VariableElement variableElement, Elements elementUtils) throws VerifyException { KickbackElement kickbackElement = variableElement.getAnnotation(KickbackElement.class); Weak weak = variableElement.getAnnotation(Weak.class); Soft soft = variableElement.getAnnotation(Soft.class); PackageElement packageElement = elementUtils.getPackageOf(variableElement); this.variableElement = variableElement; this.packageName = packageElement.isUnnamed() ? null : packageElement.getQualifiedName().toString(); this.typeName = TypeName.get(variableElement.asType()); this.clazzName = variableElement.getSimpleName().toString(); this.value = variableElement.getConstantValue(); if(weak != null) this.isWeak = true; else this.isWeak = false; if(soft != null) this.isSoft = true; else this.isSoft = false; if(kickbackElement != null) { this.elementName = StringUtils.toUpperCamel(Strings.isNullOrEmpty(kickbackElement.name()) ? this.clazzName : kickbackElement.name()); } else { this.elementName = StringUtils.toUpperCamel(this.clazzName); } checkPrimitiveType(); checkModifierValidate(); checkAnnotationValidate(); }
private StringBuilder getContainingClassOrPackageHeader(Element el, Elements elements, ElementUtilities eu) { StringBuilder sb = new StringBuilder(); if (el.getKind() != ElementKind.PACKAGE && el.getKind() != ElementKind.MODULE) { TypeElement cls = eu.enclosingTypeElement(el); if (cls != null) { switch(cls.getEnclosingElement().getKind()) { case ANNOTATION_TYPE: case CLASS: case ENUM: case INTERFACE: case PACKAGE: sb.append("<font size='+0'><b>"); //NOI18N createLink(sb, cls, makeNameLineBreakable(cls.getQualifiedName().toString())); sb.append("</b></font>"); //NOI18N) } } else { PackageElement pkg = elements.getPackageOf(el); if (pkg != null) { sb.append("<font size='+0'><b>"); //NOI18N createLink(sb, pkg, makeNameLineBreakable(pkg.getQualifiedName().toString())); sb.append("</b></font>"); //NOI18N) } } } return sb; }
private void addPackageContent(final Env env, PackageElement pe, EnumSet<ElementKind> kinds, DeclaredType baseType, boolean insideNew, boolean srcOnly) throws IOException { Set<? extends TypeMirror> smartTypes = options.contains(Options.ALL_COMPLETION) ? null : getSmartTypes(env); CompilationController controller = env.getController(); Elements elements = controller.getElements(); Types types = controller.getTypes(); Trees trees = controller.getTrees(); ElementUtilities eu = controller.getElementUtilities(); Scope scope = env.getScope(); for (Element e : pe.getEnclosedElements()) { if (e.getKind().isClass() || e.getKind().isInterface()) { String name = e.getSimpleName().toString(); if ((env.getExcludes() == null || !env.getExcludes().contains(e)) && startsWith(env, name) && (Utilities.isShowDeprecatedMembers() || !elements.isDeprecated(e)) && trees.isAccessible(scope, (TypeElement) e) && isOfKindAndType(e.asType(), e, kinds, baseType, scope, trees, types) && !Utilities.isExcluded(eu.getElementName(e, true))) { results.add(itemFactory.createTypeItem(env.getController(), (TypeElement) e, (DeclaredType) e.asType(), anchorOffset, null, elements.isDeprecated(e), insideNew, insideNew || env.isInsideClass(), true, isOfSmartType(env, e.asType(), smartTypes), false)); } } } String pkgName = pe.getQualifiedName() + "."; //NOI18N addPackages(env, pkgName, srcOnly); }
/** * Returns the non-object superclass of the type with the proper type parameters. * An absent Optional is returned if there is no non-Object superclass. */ public static Optional<DeclaredType> nonObjectSuperclass(final Types types, Elements elements, DeclaredType type) { checkNotNull(types); checkNotNull(elements); checkNotNull(type); final TypeMirror objectType = elements.getTypeElement(Object.class.getCanonicalName()).asType(); // It's guaranteed there's only a single CLASS superclass because java doesn't have multiple // class inheritance. TypeMirror superclass = getOnlyElement(FluentIterable.from(types.directSupertypes(type)) .filter(new Predicate<TypeMirror>() { @Override public boolean apply(TypeMirror input) { return input.getKind().equals(TypeKind.DECLARED) && (MoreElements.asType( MoreTypes.asDeclared(input).asElement())).getKind().equals(ElementKind.CLASS) && !types.isSameType(objectType, input); } }), null); return superclass != null ? Optional.of(MoreTypes.asDeclared(superclass)) : Optional.<DeclaredType>absent(); }
FindPosScanner( @NonNull final FileObject target, @NonNull final Trees trees, @NonNull final Elements elements, @NonNull final TreeUtilities treeUtilities, @NonNull final Collection<? extends ProfileSupport.Violation> violations, @NonNull final Result errors) { assert target != null; assert trees != null; assert elements != null; assert treeUtilities != null; assert violations != null; assert errors != null; this.target = target; this.trees = trees; this.elements = elements; this.treeUtilities = treeUtilities; this.errors = errors; for (ProfileSupport.Violation v : violations) { final ElementHandle<TypeElement> eh = v.getUsedType(); if (eh != null) { violationsByBinNames.put(eh.getBinaryName(), v); } } }
public static LJSONTypeElement create(Elements elements, Element element) { if (element.getKind() != ElementKind.CLASS) { throw new IllegalArgumentException( String.format("Only CLASS can be annotated with @%s", LIMITJSON.class.getSimpleName())); } TypeElement typeElement = (TypeElement) element; LJSONTypeElement ljsonElement = new LJSONTypeElement(); ljsonElement.typeElement = typeElement; ljsonElement.elements = elements; ArrayList<LIMITJSONVariable> list = new ArrayList<>(); List<? extends Element> enclosedElements = typeElement.getEnclosedElements(); if (!Collections.isEmpty(enclosedElements)) { for (Element ele : enclosedElements) { if (ele instanceof VariableElement) { list.add(LJSONVariableElement.create((VariableElement) ele)); } } } ljsonElement.variableElements = list; return ljsonElement; }
public void testFieldSignatureFromElement () throws Exception { InputStream in = this.prepareData(TEST_CLASS); try { JavacTask jt = prepareJavac (); Elements elements = jt.getElements(); TypeElement be = elements.getTypeElement(TEST_CLASS); ClassFile cf = new ClassFile (in, true); String className = cf.getName().getInternalName().replace('/','.'); //NOI18N List<? extends Element> members = be.getEnclosedElements(); for (Element e : members) { if (e.getKind() == ElementKind.FIELD) { String[] msig = ClassFileUtil.createFieldDescriptor((VariableElement) e); assertEquals (className,msig[0]); assertEquals (e.getSimpleName().toString(),msig[1]); Variable v = cf.getVariable (e.getSimpleName().toString()); assertNotNull (v); assertEquals (v.getDescriptor(), msig[2]); } } } finally { in.close (); } }
/** * Finds whether the given {@code TypeElement} or any of its type * ancestor contains an accessible static no-arg method * of the given name. * * @param typeElement {@code TypeElement} to search * @param methodName name of the method to be found * @param elements support instance to be used for the search * @return {@code true} if the given {@code TypeElement} contains, * whether inherited or declared directly, * a static no-argument method of the given name, * {@code false} otherwise */ private boolean containsSuiteMethod(TypeElement typeElement, Elements elements, Types types, TypeMirror testType) { List<ExecutableElement> allMethods = ElementFilter.methodsIn(elements.getAllMembers(typeElement)); for (ExecutableElement method : allMethods) { if (method.getSimpleName().contentEquals("suite") //NOI18N && method.getParameters().isEmpty()) { return method.getModifiers().contains(Modifier.STATIC) && types.isSameType(method.getReturnType(), testType); } } return false; }
private void addTypes(EnumSet<ElementKind> kinds, DeclaredType baseType, Set<? extends Element> toExclude, String prefix, int substitutionOffset, JavadocContext jdctx) { if (queryType == CompletionProvider.COMPLETION_ALL_QUERY_TYPE) { if (baseType == null) { addAllTypes(jdctx, kinds, toExclude, prefix, substitutionOffset); } else { Elements elements = jdctx.javac.getElements(); for(DeclaredType subtype : getSubtypesOf(baseType, prefix, jdctx)) { TypeElement elem = (TypeElement)subtype.asElement(); if ((toExclude == null || !toExclude.contains(elem)) && (Utilities.isShowDeprecatedMembers() || !elements.isDeprecated(elem))) items.add(JavaCompletionItem.createTypeItem(jdctx.javac, elem, subtype, substitutionOffset, jdctx.getReferencesCount(), elements.isDeprecated(elem), false, false, false, false, false, null)); } } } else { addLocalAndImportedTypes(jdctx, kinds, baseType, toExclude, prefix, substitutionOffset); hasAdditionalItems = true; } }
@Nullable private static AnnotationValue findAnnotationValue( @Nonnull final Elements elements, @Nonnull final Element typeElement, @Nonnull final String annotationClassName, @Nonnull final String parameterName ) { final AnnotationMirror mirror = getAnnotationByType( typeElement, annotationClassName ); final Map<? extends ExecutableElement, ? extends AnnotationValue> values = elements.getElementValuesWithDefaults( mirror ); final ExecutableElement annotationKey = values.keySet().stream(). filter( k -> parameterName.equals( k.getSimpleName().toString() ) ).findFirst().orElse( null ); return values.get( annotationKey ); }
public void testOpen() throws IOException { FileObject workDir = FileUtil.toFileObject(this.getWorkDir()); assertNotNull(workDir); FileObject dataDir = FileUtil.toFileObject(this.getDataDir()); assertNotNull(dataDir); FileObject srcFile = createSource(dataDir, workDir); JavaSource js = JavaSource.forFileObject(srcFile); ClasspathInfo cpInfo = js.getClasspathInfo(); CompilationInfo ci = SourceUtilsTestUtil.getCompilationInfo(js, Phase.RESOLVED); Elements elements = ci.getElements(); Element ce = elements.getTypeElement("javax.swing.JTable"); assertNotNull(ce); Object[] result = UiUtils.getOpenInfo(cpInfo, ce); assertNotNull(result); assertTrue(result[0] instanceof FileObject); assertTrue(result[1] instanceof Integer); assertEquals(srcFile, result[0]); assertEquals(7996, ((Integer) result[1]).intValue()); }
static String getPackageName(Elements elementUtils, TypeElement type) throws UnnamedPackageException { PackageElement pkg = elementUtils.getPackageOf(type); if (pkg.isUnnamed()) { throw new UnnamedPackageException(type); } return pkg.getQualifiedName().toString(); }
RequestManagerFactoryGenerator(ProcessingEnvironment processingEnv) { Elements elementUtils = processingEnv.getElementUtils(); glideType = elementUtils.getTypeElement(GLIDE_QUALIFIED_NAME); lifecycleType = elementUtils.getTypeElement(LIFECYCLE_QUALIFIED_NAME); requestManagerTreeNodeType = elementUtils.getTypeElement(REQUEST_MANAGER_TREE_NODE_QUALIFIED_NAME); requestManagerFactoryInterface = elementUtils.getTypeElement(REQUEST_MANAGER_FACTORY_QUALIFIED_NAME); TypeElement requestManagerType = elementUtils.getTypeElement(REQUEST_MANAGER_QUALIFIED_NAME); requestManagerClassName = ClassName.get(requestManagerType); }
/** * The {@link com.bumptech.glide.request.RequestOptions} subclass should always be our * generated subclass type to avoid inadvertent errors where a different subclass is applied that * accidentally wipes out some logic in overidden methods in our generated subclass. */ @Nullable private MethodSpec generateOverrideSetRequestOptions( String generatedCodePackageName, @Nullable TypeSpec generatedRequestOptions) { if (generatedRequestOptions == null) { return null; } Elements elementUtils = processingEnv.getElementUtils(); TypeElement requestOptionsType = elementUtils.getTypeElement( RequestOptionsGenerator.REQUEST_OPTIONS_QUALIFIED_NAME); TypeElement androidNonNullType = elementUtils.getTypeElement("android.support.annotation.NonNull"); // This class may have just been generated and therefore may not be found if we try to obtain // it via Elements, so use just the String version instead. String generatedRequestOptionsQualifiedName = generatedCodePackageName + "." + generatedRequestOptions.name; String methodName = "setRequestOptions"; String parameterName = "toSet"; return MethodSpec.methodBuilder(methodName) .addAnnotation(Override.class) .addModifiers(Modifier.PROTECTED) .addParameter( ParameterSpec.builder(ClassName.get(requestOptionsType), parameterName) .addAnnotation(ClassName.get(androidNonNullType)) .build()) .beginControlFlow("if ($N instanceof $L)", parameterName, generatedRequestOptionsQualifiedName) .addStatement("super.$N($N)", methodName, parameterName) .nextControlFlow("else") .addStatement("super.setRequestOptions(new $L().apply($N))", generatedRequestOptionsQualifiedName, parameterName) .endControlFlow() .build(); }
public static String getPackageName(Elements elements, TypeElement typeElement) throws NoPackageNameException { PackageElement pkg = elements.getPackageOf(typeElement); if (pkg.isUnnamed()) { throw new NoPackageNameException(typeElement); } return pkg.getQualifiedName().toString(); }
/** * Explicitly add properties that elude reflection implicit strategy * @param element * @param props */ protected boolean augmentProperties(TypeElement element, Properties props) throws InvocationTargetException, IllegalAccessException { final Elements elements = processingEnv.getElementUtils(); final TypeElement extensionTypeElement = elements.getTypeElement(stepClass.getName()); if (extensionTypeElement != null && processingEnv.getTypeUtils().isAssignable(element.asType(), extensionTypeElement.asType())) { props.put("kind", "STEP"); props.put("entrypoint", element.getQualifiedName().toString()); } else { props.put("kind", "BEAN"); props.put("entrypoint", element.getQualifiedName().toString()); for (Element method: element.getEnclosedElements()) { if (method.getAnnotation(handlerAnnotationClass) != null) { // Process method augmentProperties((ExecutableElement)method, props); addActionProperties(method, props); // Found a method annotated with Handler, let's search for // fields annotated with SyndesisActionProperty for (Element field: element.getEnclosedElements()) { if (field.getKind() == ElementKind.FIELD) { addActionProperties(field, props); } } return true; } } } return false; }
private void addLocalFieldsAndVars(final Env env) throws IOException { final CompilationController controller = env.getController(); final Elements elements = controller.getElements(); final Types types = controller.getTypes(); final Scope scope = env.getScope(); Set<? extends TypeMirror> smartTypes = options.contains(Options.ALL_COMPLETION) ? null : getSmartTypes(env); final TypeElement enclClass = scope.getEnclosingClass(); for (Element e : getLocalMembersAndVars(env)) { switch (e.getKind()) { case ENUM_CONSTANT: case EXCEPTION_PARAMETER: case LOCAL_VARIABLE: case RESOURCE_VARIABLE: case PARAMETER: results.add(itemFactory.createVariableItem(env.getController(), (VariableElement) e, e.asType(), anchorOffset, null, env.getScope().getEnclosingClass() != e.getEnclosingElement(), elements.isDeprecated(e), isOfSmartType(env, e.asType(), smartTypes), env.assignToVarPos())); break; case FIELD: String name = e.getSimpleName().toString(); if (THIS_KEYWORD.equals(name) || SUPER_KEYWORD.equals(name)) { results.add(itemFactory.createKeywordItem(name, null, anchorOffset, isOfSmartType(env, e.asType(), smartTypes))); } else { TypeMirror tm = asMemberOf(e, enclClass != null ? enclClass.asType() : null, types); results.add(itemFactory.createVariableItem(env.getController(), (VariableElement) e, tm, anchorOffset, null, env.getScope().getEnclosingClass() != e.getEnclosingElement(), elements.isDeprecated(e), isOfSmartType(env, tm, smartTypes), env.assignToVarPos())); } break; } } }
/** * Returns the set of all non-private methods from {@code type}, including methods that it * inherits from its ancestors. Inherited methods that are overridden are not included in the * result. So if {@code type} defines {@code public String toString()}, the returned set will * contain that method, but not the {@code toString()} method defined by {@code Object}. * <p/> * <p>The returned set may contain more than one method with the same signature, if * {@code type} inherits those methods from different ancestors. For example, if it * inherits from unrelated interfaces {@code One} and {@code Two} which each define * {@code void foo();}, and if it does not itself override the {@code foo()} method, * then both {@code One.foo()} and {@code Two.foo()} will be in the returned set. * * @param type the type whose own and inherited methods are to be returned * @param elementUtils an {@link Elements} object, typically returned by * {@link javax.annotation.processing.AbstractProcessor#processingEnv processingEnv}<!-- * -->.{@link javax.annotation.processing.ProcessingEnvironment.getElementUtils() * getElementUtils()} */ public static ImmutableSet<ExecutableElement> getLocalAndInheritedMethods( TypeElement type, Elements elementUtils) { SetMultimap<String, ExecutableElement> methodMap = LinkedHashMultimap.create(); getLocalAndInheritedMethods(getPackage(type), type, methodMap); // Find methods that are overridden. We do this using `Elements.overrides`, which means // that it is inherently a quadratic operation, since we have to compare every method against // every other method. We reduce the performance impact by (a) grouping methods by name, since // a method cannot override another method with a different name, and (b) making sure that // methods in ancestor types precede those in descendant types, which means we only have to // check a method against the ones that follow it in that order. Set<ExecutableElement> overridden = new LinkedHashSet<ExecutableElement>(); for (String methodName : methodMap.keySet()) { List<ExecutableElement> methodList = ImmutableList.copyOf(methodMap.get(methodName)); for (int i = 0; i < methodList.size(); i++) { ExecutableElement methodI = methodList.get(i); for (int j = i + 1; j < methodList.size(); j++) { ExecutableElement methodJ = methodList.get(j); if (elementUtils.overrides(methodJ, methodI, type)) { overridden.add(methodI); } } } } Set<ExecutableElement> methods = new LinkedHashSet<ExecutableElement>(methodMap.values()); methods.removeAll(overridden); return ImmutableSet.copyOf(methods); }
@Override public void findAndParseObjects(RoundEnvironment env, Map<String, JsonObjectHolder> jsonObjectMap, Elements elements, Types types) { for (Element element : env.getElementsAnnotatedWith(OnPreJsonSerialize.class)) { try { processOnPreJsonSerializeMethodAnnotation(element, jsonObjectMap, elements); } catch (Exception e) { StringWriter stackTrace = new StringWriter(); e.printStackTrace(new PrintWriter(stackTrace)); error(element, "Unable to generate injector for %s. Stack trace incoming:\n%s", OnPreJsonSerialize.class, stackTrace.toString()); } } }
private void processOnPreJsonSerializeMethodAnnotation(Element element, Map<String, JsonObjectHolder> jsonObjectMap, Elements elements) throws Exception { if (!isCallbackMethodAnnotationValid(element, OnPreJsonSerialize.class.getSimpleName())) { return; } TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); ExecutableElement executableElement = (ExecutableElement)element; JsonObjectHolder objectHolder = jsonObjectMap.get(TypeUtils.getInjectedFQCN(enclosingElement, elements)); objectHolder.preSerializeCallback = executableElement.getSimpleName().toString(); }
private static boolean isValueSpecMarker( TypeMirror returnType, ProcessingEnvironment processingEnvironment) { Types types = processingEnvironment.getTypeUtils(); Elements elements = processingEnvironment.getElementUtils(); return types.isSameType( returnType, elements.getTypeElement(dataenum_case.class.getCanonicalName()).asType()); }
private void addAllNonPrivateFields(Element element, Elements elements, Types types, JsonObjectHolder objectHolder) { List<? extends Element> enclosedElements = element.getEnclosedElements(); for (Element enclosedElement : enclosedElements) { ElementKind enclosedElementKind = enclosedElement.getKind(); if (enclosedElementKind == ElementKind.FIELD) { Set<Modifier> modifiers = enclosedElement.getModifiers(); if (!modifiers.contains(Modifier.PRIVATE) && !modifiers.contains(Modifier.PROTECTED) && !modifiers.contains(Modifier.TRANSIENT) && !modifiers.contains(Modifier.STATIC)) { createOrUpdateFieldHolder(enclosedElement, elements, types, objectHolder); } } } }
private void processOnCompleteMethodAnnotation(Element element, Map<String, JsonObjectHolder> jsonObjectMap, Elements elements) throws Exception { if (!isCallbackMethodAnnotationValid(element, OnJsonParseComplete.class.getSimpleName())) { return; } TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); ExecutableElement executableElement = (ExecutableElement)element; JsonObjectHolder objectHolder = jsonObjectMap.get(TypeUtils.getInjectedFQCN(enclosingElement, elements)); objectHolder.onCompleteCallback = executableElement.getSimpleName().toString(); }
public FieldEntity(Elements elementUtil, VariableElement element) { this.element = element; this.classSimpleName = element.getEnclosingElement().getSimpleName().toString(); this.classQualifiedName = ((TypeElement) element.getEnclosingElement()).getQualifiedName().toString(); this.feildName = element.getSimpleName().toString(); this.typeMirror = element.asType(); this.typeName = typeMirror.toString(); }
public static boolean isParcelableArray(Types typeUtils, Elements elementUtils, Element element) { if (element.asType().getKind() != TypeKind.ARRAY) { return false; } ArrayType arrayType = (ArrayType) element.asType(); TypeMirror componentType = arrayType.getComponentType(); TypeElement typeParcelable = elementUtils.getTypeElement(Parcelable.class.getName()); return typeUtils.isSubtype(componentType, typeParcelable.asType()); }
public void testGetTypeName() throws Exception { TestUtilities.copyStringToFileObject(testFO, "package foo;" + "public class TestClass {" + "}"); runUserActionTask(testFO, new Task<CompilationController>() { public void run(CompilationController controller) throws IOException { controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED); Elements elements = controller.getElements(); Types types = controller.getTypes(); String typeName = String.class.getName(); String resolvedTypeName = MethodModelSupport.getTypeName(elements.getTypeElement(typeName).asType()); assertEquals(typeName, resolvedTypeName); typeName = InputStream.class.getName(); resolvedTypeName = MethodModelSupport.getTypeName(elements.getTypeElement(typeName).asType()); assertEquals(typeName, resolvedTypeName); resolvedTypeName = MethodModelSupport.getTypeName(types.getPrimitiveType(TypeKind.INT)); assertEquals("int", resolvedTypeName); typeName = String.class.getName(); resolvedTypeName = MethodModelSupport.getTypeName(types.getArrayType(elements.getTypeElement(typeName).asType())); assertEquals("java.lang.String[]", resolvedTypeName); PrimitiveType primitiveType = types.getPrimitiveType(TypeKind.BYTE); ArrayType arrayType = types.getArrayType(primitiveType); resolvedTypeName = MethodModelSupport.getTypeName(arrayType); assertEquals("byte[]", resolvedTypeName); } }); }
public void replaceIfNeed(Elements elements, ProcessorPrinter pp) { //pp.note("TypeCompat", "replaceIfNeed", "start check element: " + tm.toString()); Element te = getElement(); //when TypeMirror is primitive , here te is null. if(te == null) { pp.note("TypeCompat", "replaceIfNeed", "Element = null"); }else{ boolean needReplace = false; //when depend another interface(@Fields) need replace. Note: @Retention CLASS List<? extends AnnotationMirror> mirrors = getElementAsType().getAnnotationMirrors(); for(AnnotationMirror am : mirrors){ DeclaredType type = am.getAnnotationType(); // pp.note("TypeCompat", "replaceIfNeed", "type = " + type); if(type.toString().equals(Fields.class.getName())){ needReplace = true; break; } } if(needReplace){ TypeElement typeElement = getElementAsType(); String packageName = elements.getPackageOf(typeElement).getQualifiedName().toString(); mTypeName_impl = ClassName.get(packageName, Util.getTargetClassName(packageName, typeElement.getQualifiedName().toString()) + DataMediatorConstants.IMPL_SUFFIX ); } } }
/** * Returns set of names of classes of the classType type. * * @param classpathMap map of classpaths of all project files * @param classType return only classes of this type * @return set of class names */ public static Set<String> getAppClassNames(@NonNull Collection<? extends FileObject> roots, final @NonNull String classType) { final Set<String> appClassNames = new HashSet<>(); for (FileObject fo : roots) { final ClasspathInfo cpInfo = ClasspathInfo.create(fo); final JavaSource js = JavaSource.create(cpInfo); if (js != null) { try { js.runUserActionTask(new Task<CompilationController>() { @Override public void run(CompilationController controller) throws Exception { final ClassIndex classIndex = cpInfo.getClassIndex(); final Elements elems = controller.getElements(); TypeElement fxAppElement = elems.getTypeElement(classType); ElementHandle<TypeElement> appHandle = ElementHandle.create(fxAppElement); Set<ElementHandle<TypeElement>> appHandles = classIndex.getElements(appHandle, kinds, scopes); for (ElementHandle<TypeElement> elemHandle : appHandles) { appClassNames.add(elemHandle.getQualifiedName()); } } }, true); } catch (Exception e) { } } } return appClassNames; }
@SuppressWarnings( "SameParameterValue" ) @Nullable static DeclaredType getTypeMirrorAnnotationParameter( @Nonnull final Elements elements, @Nonnull final Element typeElement, @Nonnull final String annotationClassName, @Nonnull final String parameterName ) { final AnnotationValue annotationValue = findAnnotationValue( elements, typeElement, annotationClassName, parameterName ); return null == annotationValue ? null : (DeclaredType) annotationValue.getValue(); }
@Override public CI createArrayItem(CompilationInfo info, ArrayType type, int substitutionOffset, ReferencesCount referencesCount, Elements elements) { int dim = 0; TypeMirror tm = type; while(tm.getKind() == TypeKind.ARRAY) { tm = ((ArrayType)tm).getComponentType(); dim++; } if (tm.getKind().isPrimitive()) { String kwd = tm.toString(); StringBuilder sb = new StringBuilder(kwd); for(int i = 0; i < dim; i++) { sb.append("[]"); //NOI18N } return new CI(sb.toString(), 670 - SMART_TYPE, kwd); } if (tm.getKind() == TypeKind.DECLARED || tm.getKind() == TypeKind.ERROR) { DeclaredType dt = (DeclaredType)tm; TypeElement elem = (TypeElement)dt.asElement(); String simpleName = elem.getSimpleName().toString(); String fqn = elem.getQualifiedName().toString(); int weight = 50; if (fqn.startsWith("java.lang") || fqn.startsWith("java.util")) { // NOI18N weight -= 10; } else if (fqn.startsWith("org.omg") || fqn.startsWith("org.apache")) { // NOI18N weight += 10; } else if (fqn.startsWith("com.sun") || fqn.startsWith("com.ibm") || fqn.startsWith("com.apple")) { // NOI18N weight += 20; } else if (fqn.startsWith("sun") || fqn.startsWith("sunw") || fqn.startsWith("netscape")) { // NOI18N weight += 30; } return new CI(simpleName, 800 - SMART_TYPE, referencesCount != null ? simpleName + '#' + weight + '#' + info.getElementUtilities().getElementName(elem.getEnclosingElement(), true) : simpleName); } throw new IllegalArgumentException("array element kind=" + tm.getKind()); }
private Element createElement(ASTService ast, Elements elements, String name, Element original, ModuleElement modle) { Element el = elementCache.get(name); if (el == null) { if (original != null) { if (original.getKind().isClass() || original.getKind().isInterface()) { elementCache.put(name, el = new TypeElementWrapper(ast, elements, (TypeElement) original)); return el; } if (original.getKind() == ElementKind.PACKAGE) { elementCache.put(name, el = new PackageElementWrapper(ast, elements, (PackageElement) original)); return el; } return original; } int lastDot = name.lastIndexOf('.'); Name simpleName = elements.getName(name.substring(lastDot + 1)); Name fqnName = elements.getName(name); if (classes.containsKey(name)) { Element parent = lastDot > 0 ? resolve(ast, elements, name.substring(0, lastDot), modle) : elements.getPackageElement(""); elementCache.put(name, el = new FakeTypeElement(ast, elements, simpleName, fqnName, name, parent, classes.get(name), modle)); } else if (packages.contains(name)) { elementCache.put(name, el = new FakePackageElement(ast, elements, fqnName, name, simpleName, modle)); } else { return null;//XXX: handling of this null in callers! } } return el; }
public SearchAnnotations(Trees trees, Elements elements) { this.trees = trees; this.elements = elements; this.triggersCompleteAnnotation = elements.getTypeElement(TriggersComplete.class.getName()); this.triggersCompleteRepeatAnnotation = elements.getTypeElement(TriggersCompleteRepeat.class.getName()); }