Java Code Examples for javax.lang.model.element.Element#toString()
The following examples show how to use
javax.lang.model.element.Element#toString() .
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: SiddhiAnnotationProcessor.java From siddhi with Apache License 2.0 | 6 votes |
private String getMatchingSuperClass(Element elementToValidate, String[] superClassNames) { TypeMirror superType = ((TypeElement) elementToValidate).getSuperclass(); String superClass = null; // Looping the inheritance hierarchy to check if the element inherits at least one of the super // classes specified. while (!"none".equals(superType.toString())) { Element superTypeElement = ((DeclaredType) superType).asElement(); if (Arrays.asList(superClassNames).contains(superTypeElement.toString())) { superClass = superTypeElement.toString(); break; } superType = ((TypeElement) superTypeElement).getSuperclass(); } return superClass; }
Example 2
Source File: TestGetElementReference.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
private static String symbolToString(Element el) { switch (el.getKind()) { case METHOD: return symbolToString(el.getEnclosingElement()) + "." + el.toString(); case CONSTRUCTOR: return symbolToString(el.getEnclosingElement().getEnclosingElement()) + "." + el.toString(); default: return el.toString(); } }
Example 3
Source File: ObjectRouterGenerator.java From componentrouter with Apache License 2.0 | 5 votes |
private void instanceConstructorBuilder(MethodSpec.Builder methodBuilder, Element enclosedElement, Map<Integer, List<StringBuilder[]>> map, String paramsName, ClassName targetClassName) { ConstructorRouter annotation = enclosedElement.getAnnotation(ConstructorRouter.class); if (annotation == null) { return; } String str = enclosedElement.toString(); str = str.substring(str.indexOf("(") + 1, str.indexOf(")")); if (str.isEmpty()) { methodBuilder.beginControlFlow("if($L==null||$L.length==0)", paramsName, paramsName); methodBuilder.addStatement("$L=new $T()", INSTANCE_FIELD_NAME, targetClassName); methodBuilder.addStatement("return"); methodBuilder.endControlFlow(); return; } String[] argTypes = str.split(","); int len = argTypes.length; if (argTypes[len - 1].endsWith("...")) { return; } List<StringBuilder[]> stringBuilders = map.get(len); if (stringBuilders == null) { stringBuilders = new ArrayList<>(); map.put(len, stringBuilders); } StringBuilder[] builders = new StringBuilder[2]; stringBuilders.add(builders); StringBuilder code = new StringBuilder(); StringBuilder argBuilder = new StringBuilder(); builders[0] = code; builders[1] = argBuilder; for (int i = 0; i < argTypes.length; i++) { String argType = argTypes[i]; if (code.length() > 0) { code.append("\n&&"); argBuilder.append(","); } code.append("(").append(argType).append(".class.isAssignableFrom(").append(paramsName).append("[").append(i).append("].getClass()))"); argBuilder.append("(").append(argType).append(")").append(paramsName).append("[").append(i).append("]"); } }
Example 4
Source File: TestGetElementReference.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
private static String symbolToString(Element el) { switch (el.getKind()) { case METHOD: return symbolToString(el.getEnclosingElement()) + "." + el.toString(); case CONSTRUCTOR: return symbolToString(el.getEnclosingElement().getEnclosingElement()) + "." + el.toString(); default: return el.toString(); } }
Example 5
Source File: ToothpickProcessor.java From toothpick with Apache License 2.0 | 5 votes |
private boolean isValidInjectedElementKind(VariableElement injectedTypeElement) { Element typeElement = typeUtils.asElement(injectedTypeElement.asType()); // typeElement can be null for primitives. // https://github.com/stephanenicolas/toothpick/issues/261 if (typeElement == null // || typeElement.getKind() != ElementKind.CLASS // && typeElement.getKind() != ElementKind.INTERFACE // && typeElement.getKind() != ElementKind.ENUM) { // find the class containing the element // the element can be a field or a parameter Element enclosingElement = injectedTypeElement.getEnclosingElement(); final String typeName; if (typeElement != null) { typeName = typeElement.toString(); } else { typeName = injectedTypeElement.asType().toString(); } if (enclosingElement instanceof TypeElement) { error( injectedTypeElement, "Field %s#%s is of type %s which is not supported by Toothpick.", ((TypeElement) enclosingElement).getQualifiedName(), injectedTypeElement.getSimpleName(), typeName); } else { Element methodOrConstructorElement = enclosingElement; enclosingElement = enclosingElement.getEnclosingElement(); error( injectedTypeElement, "Parameter %s in method/constructor %s#%s is of type %s which is not supported by Toothpick.", injectedTypeElement.getSimpleName(), // ((TypeElement) enclosingElement).getQualifiedName(), // methodOrConstructorElement.getSimpleName(), // typeName); } return false; } return true; }
Example 6
Source File: TestGetElementReference.java From jdk8u60 with GNU General Public License v2.0 | 5 votes |
private static String symbolToString(Element el) { switch (el.getKind()) { case METHOD: return symbolToString(el.getEnclosingElement()) + "." + el.toString(); case CONSTRUCTOR: return symbolToString(el.getEnclosingElement().getEnclosingElement()) + "." + el.toString(); default: return el.toString(); } }
Example 7
Source File: InjectPresenterProcessor.java From Moxy with MIT License | 5 votes |
private static List<TargetPresenterField> collectFields(TypeElement presentersContainer) { List<TargetPresenterField> fields = new ArrayList<>(); for (Element element : presentersContainer.getEnclosedElements()) { if (element.getKind() != ElementKind.FIELD) { continue; } AnnotationMirror annotation = Util.getAnnotation(element, PRESENTER_FIELD_ANNOTATION); if (annotation == null) { continue; } // TODO: simplify? TypeMirror clazz = ((DeclaredType) element.asType()).asElement().asType(); String name = element.toString(); String type = Util.getAnnotationValueAsString(annotation, "type"); String tag = Util.getAnnotationValueAsString(annotation, "tag"); String presenterId = Util.getAnnotationValueAsString(annotation, "presenterId"); TargetPresenterField field = new TargetPresenterField(clazz, name, type, tag, presenterId); fields.add(field); } return fields; }
Example 8
Source File: ObjectMappableProcessor.java From sqlbrite-dao with Apache License 2.0 | 5 votes |
/** * Check the Element if it's a class and returns the corresponding TypeElement * * @param e The element to check * @return The {@link TypeElement} representing the annotated class * @throws ProcessingException If element is not a CLASS */ private TypeElement checkAndGetClass(Element e) throws ProcessingException { if (e.getKind() != ElementKind.CLASS) { throw new ProcessingException(e, "%s is annotated with @%s but only classes can be annotated with this annotation", e.toString(), ObjectMappable.class.getSimpleName()); } return (TypeElement) e; }
Example 9
Source File: JavadocHelper.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
private String elementSignature(Element el) { switch (el.getKind()) { case ANNOTATION_TYPE: case CLASS: case ENUM: case INTERFACE: return ((TypeElement) el).getQualifiedName().toString(); case FIELD: return elementSignature(el.getEnclosingElement()) + "." + el.getSimpleName() + ":" + el.asType(); case ENUM_CONSTANT: return elementSignature(el.getEnclosingElement()) + "." + el.getSimpleName(); case EXCEPTION_PARAMETER: case LOCAL_VARIABLE: case PARAMETER: case RESOURCE_VARIABLE: return el.getSimpleName() + ":" + el.asType(); case CONSTRUCTOR: case METHOD: StringBuilder header = new StringBuilder(); header.append(elementSignature(el.getEnclosingElement())); if (el.getKind() == ElementKind.METHOD) { header.append("."); header.append(el.getSimpleName()); } header.append("("); String sep = ""; ExecutableElement method = (ExecutableElement) el; for (Iterator<? extends VariableElement> i = method.getParameters().iterator(); i.hasNext();) { VariableElement p = i.next(); header.append(sep); header.append(p.asType()); sep = ", "; } header.append(")"); return header.toString(); default: return el.toString(); } }
Example 10
Source File: TurbineElements.java From turbine with Apache License 2.0 | 5 votes |
@Override public boolean isDeprecated(Element element) { if (!(element instanceof TurbineElement)) { throw new IllegalArgumentException(element.toString()); } for (AnnoInfo a : ((TurbineTypeElement) element).annos()) { if (a.sym().equals(ClassSymbol.DEPRECATED)) { return true; } } return false; }
Example 11
Source File: TestGetElementReference.java From hottub with GNU General Public License v2.0 | 5 votes |
private static String symbolToString(Element el) { switch (el.getKind()) { case METHOD: return symbolToString(el.getEnclosingElement()) + "." + el.toString(); case CONSTRUCTOR: return symbolToString(el.getEnclosingElement().getEnclosingElement()) + "." + el.toString(); default: return el.toString(); } }
Example 12
Source File: EasyMVPProcessor.java From EasyMVP with Apache License 2.0 | 5 votes |
private void parsePresenterId(Element element, Map<TypeElement, DelegateClassGenerator> delegateClassMap) { if (!SuperficialValidation.validateElement(element)) { error("Superficial validation error for %s", element.getSimpleName()); return; } if (Validator.isPrivate(element)) { error("%s can't be private", element.getSimpleName()); return; } if (Validator.isMethod(element)) { ExecutableType emeth = (ExecutableType) element.asType(); if (!emeth.getReturnType().getKind().equals(TypeKind.LONG) && !emeth.getReturnType().getKind().equals(TypeKind.INT)) { error("%s must have return type int or long", element); } } else { TypeKind kind = element.asType().getKind(); if (kind != TypeKind.INT && kind != TypeKind.LONG) { error("%s must be int or long", element.getSimpleName()); return; } } String presenterId = element.toString(); DelegateClassGenerator delegateClassGenerator = getDelegate((TypeElement) element.getEnclosingElement(), delegateClassMap); delegateClassGenerator.setPresenterId(presenterId); }
Example 13
Source File: CompositeControllerAnnotationScanner.java From nalu with Apache License 2.0 | 4 votes |
private CompositeModel handleComposite(Element element) throws ProcessorException { // get Annotation ... CompositeController annotation = element.getAnnotation(CompositeController.class); // handle ... TypeElement componentTypeElement = this.getComponentTypeElement(annotation); if (componentTypeElement == null) { throw new ProcessorException("Nalu-Processor: componentTypeElement is null"); } TypeElement componentInterfaceTypeElement = this.getComponentInterfaceTypeElement(annotation); TypeMirror componentTypeTypeMirror = this.getComponentType(element.asType()); if (Objects.isNull(componentTypeTypeMirror)) { throw new ProcessorException("Nalu-Processor: componentTypeTypeMirror is null"); } // check and save the component type ... if (metaModel.getComponentType() == null) { metaModel.setComponentType(new ClassNameModel(componentTypeTypeMirror.toString())); } else { ClassNameModel compareValue = new ClassNameModel(componentTypeTypeMirror.toString()); if (!metaModel.getComponentType() .equals(compareValue)) { throw new ProcessorException("Nalu-Processor: componentType >>" + compareValue.getClassName() + "<< is different. All composite controllers must implement the componentType!"); } } // check, if the controller implements IsComponentController boolean componentController = this.checkIsComponentCreator(element, componentInterfaceTypeElement); // get context! String context = this.getContextType(element); if (Objects.isNull(context)) { throw new ProcessorException("Nalu-Processor: composite controller >>" + element.toString() + "<< does not have a context generic!"); } // create model ... if (Objects.isNull(componentInterfaceTypeElement)) { throw new ProcessorException("Nalu-Processor: componentInterfaceTypeElement is null!"); } return new CompositeModel(new ClassNameModel(context), new ClassNameModel(element.toString()), new ClassNameModel(componentInterfaceTypeElement.toString()), new ClassNameModel(componentTypeElement.toString()), componentController); }
Example 14
Source File: LetvPluginAnnotationProcessor.java From letv with Apache License 2.0 | 4 votes |
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { Messager messager = this.processingEnv.getMessager(); messager.printMessage(Kind.NOTE, "实现@LetvClassAutoLoad注解的class 数量: " + annotations.size()); if (annotations.size() > 0) { String path = "./app/src/main/assets/"; File folder = new File(path); if (!folder.exists()) { folder.mkdir(); } try { File staticJsonFile = new File(path + "static.txt"); if (!staticJsonFile.exists()) { staticJsonFile.createNewFile(); } InputStreamReader inputReader = new InputStreamReader(new FileInputStream(staticJsonFile)); BufferedReader bufReader = new BufferedReader(inputReader); Set<String> resultSet = new HashSet(); while (true) { String line = bufReader.readLine(); if (line == null) { break; } resultSet.add(line); } bufReader.close(); inputReader.close(); boolean hasDif = false; for (TypeElement te : annotations) { for (Element e : roundEnv.getElementsAnnotatedWith(te)) { String className = e.toString(); if (!resultSet.contains(className)) { resultSet.add(className); hasDif = true; } } } if (hasDif) { messager.printMessage(Kind.NOTE, "更新class映射文件 static.txt"); BufferedWriter outPut = new BufferedWriter(new FileWriter(staticJsonFile)); for (String str : resultSet) { outPut.write(str + "\n"); messager.printMessage(Kind.NOTE, "写入中: " + str); } outPut.close(); messager.printMessage(Kind.NOTE, "更新class映射文件 static.txt 成功"); } else { messager.printMessage(Kind.NOTE, "不存在未包含 class name"); return true; } } catch (IOException e2) { e2.printStackTrace(); messager.printMessage(Kind.NOTE, "更新class映射文件static.txt 失败 : /app/src/main/assets/ 路径无效,请检查路径"); } } return true; }
Example 15
Source File: AndroidRouterProcessor.java From Android-Router with Apache License 2.0 | 4 votes |
private void parseRouterModule(Element moduleEle, List<? extends Element> allEle, List<JavaFile> javaFiles) { RouterModule moduleAnno = moduleEle.getAnnotation(RouterModule.class); String schemes = moduleAnno.scheme(); String host = moduleAnno.host().toLowerCase(); if (isEmpty(schemes) || isEmpty(host)) return; // constructor build MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder(); constructorBuilder.addModifiers(Modifier.PUBLIC).addException(Exception.class); // constructor body ClassName original = ClassName.get(elementUtils.getPackageOf(moduleEle).toString(), moduleEle.getSimpleName().toString()); constructorBuilder.addStatement("this.original = $T.class.newInstance()", original) .addStatement("this.mapping = new $T()", HashMap.class); // parse RouterPath int size = allEle.size(); for (int i = 0; i < size; i++) { Element elm = allEle.get(i); RouterPath pathAnno = elm.getAnnotation(RouterPath.class); if (pathAnno == null) continue; String agrs = ((ExecutableElement) elm).getParameters().toString(); String types = ""; String methodFullTypes = elm.toString(); int start = methodFullTypes.indexOf("("); int end = methodFullTypes.indexOf(")"); if (end - start > 1) { // open1(java.lang.String,com.tangxiaolv.router.Promise) => // ,java.lang.String.class,com.tangxiaolv.router.Promise.class)) types = methodFullTypes.substring(start + 1, end); if (types.lastIndexOf("...") != -1) types = types.replace("...", "[]"); methodFullTypes = "," + getFullTypesString(types) + "))"; } else { methodFullTypes = "))"; } String methodKey = pathAnno.value().toLowerCase(); String methodName = elm.getSimpleName().toString(); // add method constructorBuilder.addStatement( "mapping.put($S + $T._METHOD, original.getClass().getMethod($S" + methodFullTypes, methodKey, MODULE_DELEGATER, methodName); // add params name constructorBuilder.addStatement("String args$L = $S", i, agrs); constructorBuilder.addStatement("mapping.put($S + $T._ARGS, args$L)", methodKey, MODULE_DELEGATER, i); // add params type constructorBuilder.addStatement("String type$L = $S", i, types); constructorBuilder.addStatement("mapping.put($S + $T._TYPES, type$L)", methodKey, MODULE_DELEGATER, i) .addCode("\n"); } // method build MethodSpec.Builder invokeBuilder = MethodSpec.methodBuilder("invoke"); invokeBuilder.addModifiers(Modifier.PUBLIC, Modifier.FINAL) .returns(void.class) .addParameter(String.class, "path") .addParameter(PARAMS_WRAPPER, "params") .addException(Exception.class); // method body invokeBuilder.addStatement("$T.invoke(path,params,original,mapping)", MODULE_DELEGATER); // check multi schemes String scheme_main = schemes.contains("|") ? schemes.split("\\|")[0] : schemes; // java file build String mirror_name_main = PREFIX + scheme_main + "_" + host; TypeSpec clazz = TypeSpec.classBuilder(mirror_name_main) .addModifiers(Modifier.PUBLIC, Modifier.FINAL).addSuperinterface(IMIRROR) // Fields .addFields(buildRouterModuleFields()) // constructor .addMethod(constructorBuilder.build()) // Methods .addMethod(invokeBuilder.build()) // doc .addJavadoc(FILE_DOC) .build(); JavaFile javaFile = JavaFile.builder(PACKAGE_NAME, clazz).build(); javaFiles.add(javaFile); if (!schemes.equals(scheme_main)) { makeSubFile(schemes, host, ClassName.get(PACKAGE_NAME, mirror_name_main), javaFiles); } }
Example 16
Source File: TurbineElements.java From turbine with Apache License 2.0 | 4 votes |
private static Symbol asSymbol(Element element) { if (!(element instanceof TurbineElement)) { throw new IllegalArgumentException(element.toString()); } return ((TurbineElement) element).sym(); }
Example 17
Source File: UnifyAccessType.java From netbeans with Apache License 2.0 | 4 votes |
private boolean isJPAAttrAnnotation(CompilationInfo cinfo, AnnotationTree ann){ TreePath path = cinfo.getTrees().getPath(cinfo.getCompilationUnit(), ann.getAnnotationType()); Element elem = cinfo.getTrees().getElement(path); String annType = elem.toString(); return JPAAnnotations.MEMBER_LEVEL.contains(annType); }
Example 18
Source File: NaluPluginGwtProcessor.java From nalu with Apache License 2.0 | 4 votes |
private void generate(Element enclosingElement, List<SelectorMetaModel> models) throws ProcessorException { ClassNameModel enclosingClassNameModel = new ClassNameModel(enclosingElement.toString()); TypeSpec.Builder typeSpec = TypeSpec.classBuilder(enclosingElement.getSimpleName() + NaluPluginGwtProcessor.IMPL_NAME) .superclass(ClassName.get(AbstractSelectorProvider.class)) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addSuperinterface(ParameterizedTypeName.get(ClassName.get(IsSelectorProvider.class), enclosingClassNameModel.getTypeName())); // constructor ... MethodSpec constructor = MethodSpec.constructorBuilder() .addModifiers(Modifier.PUBLIC) .addStatement("super()") .build(); typeSpec.addMethod(constructor); // method "initialize" MethodSpec.Builder initializeMethod = MethodSpec.methodBuilder("initialize") .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addParameter(ParameterSpec.builder(ClassName.get(enclosingClassNameModel.getPackage(), enclosingClassNameModel.getSimpleName()), "component") .build()) .addAnnotation(Override.class); models.forEach(model -> { initializeMethod.addStatement("$T.get().getSelectorCommands().put($S, $L)", ClassName.get(SelectorProvider.class), model.selector, TypeSpec.anonymousClassBuilder("") .addSuperinterface(SelectorCommand.class) .addMethod(MethodSpec.methodBuilder("append") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .addParameter(ParameterSpec.builder(ClassName.get(IsWidget.class), "widget") .build()) .addStatement("component.$L(widget.asWidget())", model.getSelectorElement() .getSimpleName() .toString()) .build()) .build()) .build(); }); typeSpec.addMethod(initializeMethod.build()); // method "remove" MethodSpec.Builder removeMethod = MethodSpec.methodBuilder("removeSelectors") .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addAnnotation(Override.class); models.forEach(model -> { removeMethod.addStatement("$T.get().getSelectorCommands().remove($S)", ClassName.get(SelectorProvider.class), model.getSelector()) .build(); }); typeSpec.addMethod(removeMethod.build()); JavaFile javaFile = JavaFile.builder(enclosingClassNameModel.getPackage(), typeSpec.build()) .build(); try { // System.out.println(javaFile.toString()); javaFile.writeTo(this.processingEnv.getFiler()); } catch (IOException e) { throw new ProcessorException("Unable to write generated file: >>" + enclosingElement.getSimpleName() + NaluPluginGwtProcessor.IMPL_NAME + "<< -> exception: " + e.getMessage()); } }
Example 19
Source File: ConnectorAttributeProcessor.java From smallrye-reactive-messaging with Apache License 2.0 | 4 votes |
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { if (invoked) { return true; } invoked = true; Set<? extends Element> annotated = roundEnv.getElementsAnnotatedWith(ConnectorAttributes.class); Set<? extends Element> others = roundEnv.getElementsAnnotatedWith(ConnectorAttribute.class); Set<Element> all = new LinkedHashSet<>(); all.addAll(annotated); all.addAll(others); for (Element annotatedElement : all) { String className = annotatedElement.toString(); Connector connector = getConnector(annotatedElement); ConnectorAttributes annotation = annotatedElement.getAnnotation(ConnectorAttributes.class); ConnectorAttribute[] attributes; if (annotation == null) { attributes = new ConnectorAttribute[] { annotatedElement.getAnnotation(ConnectorAttribute.class) }; } else { attributes = annotation.value(); } List<ConnectorAttribute> incomingAttributes = new ArrayList<>(); List<ConnectorAttribute> outgoingAttributes = new ArrayList<>(); List<ConnectorAttribute> commonAttributes = new ArrayList<>(); for (ConnectorAttribute attribute : attributes) { addAttributeToList(commonAttributes, attribute, ConnectorAttribute.Direction.INCOMING_AND_OUTGOING); addAttributeToList(incomingAttributes, attribute, ConnectorAttribute.Direction.INCOMING); addAttributeToList(outgoingAttributes, attribute, ConnectorAttribute.Direction.OUTGOING); } validate(commonAttributes); validate(incomingAttributes); validate(outgoingAttributes); ConfigurationClassWriter classWriter = new ConfigurationClassWriter(processingEnv); ConfigurationDocWriter docWriter = new ConfigurationDocWriter(processingEnv); try { classWriter.generateAllClasses(connector, className, commonAttributes, incomingAttributes, outgoingAttributes); docWriter.generateIncomingDocumentation(connector, commonAttributes, incomingAttributes); docWriter.generateOutgoingDocumentation(connector, commonAttributes, outgoingAttributes); } catch (IOException e) { throw new RuntimeException(e); } } return true; }
Example 20
Source File: TypeHelper.java From magic-starter with GNU Lesser General Public License v3.0 | 4 votes |
private String getQualifiedName(Element element) { if (element instanceof QualifiedNameable) { return ((QualifiedNameable) element).getQualifiedName().toString(); } return element.toString(); }