Java Code Examples for javax.lang.model.element.TypeElement.getQualifiedName()

The following are Jave code examples for showing how to use getQualifiedName() of the javax.lang.model.element.TypeElement class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: GitHub   File: Mirrors.java   View Source Code Vote up 6 votes
static AttributeTypeKind from(TypeMirror type) {
  if (type.getKind() == TypeKind.DECLARED) {
    TypeElement typeElement = toElement(type);
    if (typeElement.getKind() == ElementKind.ENUM) {
      return ENUM;
    }
    if (typeElement.getKind() == ElementKind.ANNOTATION_TYPE) {
      return ANNOTATION;
    }
    Name qualifiedName = typeElement.getQualifiedName();
    if (qualifiedName.contentEquals(Class.class.getName())) {
      return TYPE;
    }
    if (qualifiedName.contentEquals(String.class.getName())) {
      return STRING;
    }
  } else if (type.getKind().isPrimitive()) {
    return PRIMITIVE;
  }
  throw new AssertionError();
}
 
Example 2
Project: incubator-netbeans   File: ReplaceBufferByString.java   View Source Code Vote up 6 votes
@Override
public Boolean visitNewClass(NewClassTree node, Void p) {
    TypeMirror tm = ci.getTrees().getTypeMirror(getCurrentPath());
    if (tm == null || tm.getKind() != TypeKind.DECLARED) {
        return false;
    }
    TypeElement el = (TypeElement)((DeclaredType)tm).asElement();
    if (el == null) {
        return false;
    }
    Name n = el.getQualifiedName();
    boolean res = n.contentEquals("java.lang.StringBuilder") || n.contentEquals("java.lang.StringBuffer"); // NOI18N
    // check if there is some initial contents
    if (node.getArguments().size() == 1 && 
            Utilities.isJavaString(ci, ci.getTrees().getTypeMirror(new TreePath(getCurrentPath(), node.getArguments().get(0))))) {
        hasContents = true;
    }
    return res;
}
 
Example 3
Project: incubator-netbeans   File: Utilities.java   View Source Code Vote up 6 votes
public static String target2String(TypeElement target) {
    final Name qualifiedName = target.getQualifiedName(); //#130759
    if (qualifiedName == null) {
        Logger.getLogger(Utilities.class.getName()).warning("Target qualified name could not be resolved."); //NOI18N
        return ""; //NOI18N
    } else {
        String qnString = qualifiedName.toString();
        if (qnString.length() == 0) {
            //probably an anonymous class
            qnString = target.asType().toString();
        }

        try {
            qnString = XMLUtil.toElementContent(qnString);
        } catch (CharConversionException ex) {
            Logger.getLogger(Utilities.class.getName()).log(Level.FINE, null, ex);
        }

        return qnString;
    }
}
 
Example 4
Project: incubator-netbeans   File: Utilities.java   View Source Code Vote up 6 votes
/**
 * Determines if the element corresponds to never-returning, terminating method.
 * System.exit, Runtime.exit, Runtime.halt are checked. The passed element is
 * usually a result of {@code CompilationInfo.getTrees().getElement(path)}.
 * 
 * @param info context
 * @param e element to check
 * @return true, if the element corrresponds to a VM-exiting method
 */
public static boolean isSystemExit(CompilationInfo info, Element e) {
    if (e == null || e.getKind() != ElementKind.METHOD) {
        return false;
    }
    ExecutableElement ee = (ExecutableElement)e;
    Name n = ee.getSimpleName();
    if (n.contentEquals("exit") || n.contentEquals("halt")) { // NOI18N
        TypeElement tel = info.getElementUtilities().enclosingTypeElement(e);
        if (tel == null) {
            return false;
        }
        Name ofqn = tel.getQualifiedName();
        if (ofqn.contentEquals("java.lang.System") || ofqn.contentEquals("java.lang.Runtime")) { // NOI18N
            return true;
        }
    }
    return false;
}
 
Example 5
Project: autoproxy   File: CommonClassGenerator.java   View Source Code Vote up 6 votes
/** Extract reflection Class<?> information from type element. */
@NonNull
public static Class<?> extractClass(@NonNull final TypeElement te) throws ClassNotFoundException {
    final Name name;

    if (te instanceof Symbol.ClassSymbol) {
        final Symbol.ClassSymbol cs = (Symbol.ClassSymbol) te;

        // this method is more accurate for nested classes
        name = cs.flatName();
    } else {
        name = te.getQualifiedName();
    }

    final String className = name.toString();

    try {
        return Class.forName(className).asSubclass(Annotation.class);
    } catch (ClassNotFoundException ex) {
        // it can be sub-type, try another approach bellow
    }

    final int dot = className.lastIndexOf(".");
    final String innerFix2 = className.substring(0, dot) + "$" + className.substring(dot + 1);
    return Class.forName(innerFix2).asSubclass(Annotation.class);
}
 
Example 6
Project: RxPay   File: ClassEntity.java   View Source Code Vote up 6 votes
/**
 * @param elementUtils
 * @param typeUtils
 * @param element      current anntated class
 */
public ClassEntity(Elements elementUtils, Types typeUtils, TypeElement element) {
    elementWeakCache = new WeakReference<TypeElement>(element);
    this.classPackageName = elementUtils.getPackageOf(element).getQualifiedName().toString();
    this.modifierSet = element.getModifiers();
    this.className = element.toString();
    annotationMirrors = element.getAnnotationMirrors();
    this.classSimpleName = element.getSimpleName();
    this.classQualifiedName = element.getQualifiedName();
    if ("java.lang.Object".equals(element.getSuperclass().toString())){
        this.superclass = null;
    }else{
        this.superclass = element.getSuperclass().toString();
    }
    List<? extends TypeMirror> interfaces = element.getInterfaces();

    for (TypeMirror anInterface : interfaces){
        this.interfaces.add(typeUtils.asElement(anInterface).toString());
    }
}
 
Example 7
Project: DDComponentForAndroid   File: AutowiredProcessor.java   View Source Code Vote up 6 votes
/**
 * Categories field, find his papa.
 *
 * @param elements Field need autowired
 */
private void categories(Set<? extends Element> elements) throws IllegalAccessException {
    if (CollectionUtils.isNotEmpty(elements)) {
        for (Element element : elements) {
            TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();

            if (element.getModifiers().contains(Modifier.PRIVATE)) {
                throw new IllegalAccessException("The autowired fields CAN NOT BE 'private'!!! please check field ["
                        + element.getSimpleName() + "] in class [" + enclosingElement.getQualifiedName() + "]");
            }

            if (parentAndChild.containsKey(enclosingElement)) { // Has categries
                parentAndChild.get(enclosingElement).add(element);
            } else {
                List<Element> childs = new ArrayList<>();
                childs.add(element);
                parentAndChild.put(enclosingElement, childs);
            }
        }

        logger.info("categories finished.");
    }
}
 
Example 8
Project: openjdk-jdk10   File: ServiceProviderProcessor.java   View Source Code Vote up 5 votes
private void writeProviderFile(TypeElement serviceProvider, String interfaceName) {
    String filename = "META-INF/providers/" + serviceProvider.getQualifiedName();
    try {
        FileObject file = processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", filename, serviceProvider);
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(file.openOutputStream(), "UTF-8"));
        writer.println(interfaceName);
        writer.close();
    } catch (IOException e) {
        processingEnv.getMessager().printMessage(isBug367599(e) ? Kind.NOTE : Kind.ERROR, e.getMessage(), serviceProvider);
    }
}
 
Example 9
Project: alvisnlp   File: ModelContext.java   View Source Code Vote up 5 votes
/**
    * Returns the target type of the specified type element representing a parameter converter class.
    * @param converterElement
    * @throws ModelException
    */
String getTargetType(TypeElement converterElement) throws ModelException {
       for (AnnotationMirror am : converterElement.getAnnotationMirrors()) {
           Element ae = typeUtils.asElement(am.getAnnotationType());
           if (ae.equals(converterAnnotation))
               for (Map.Entry<? extends ExecutableElement,? extends AnnotationValue> e : am.getElementValues().entrySet())
                   if ("targetType".equals(e.getKey().getSimpleName().toString()))
                       return e.getValue().toString();
       }
       throw new ModelException("cannot read target type for converter: " + converterElement.getQualifiedName());
}
 
Example 10
Project: GitHub   File: ButterKnifeProcessor.java   View Source Code Vote up 4 votes
private void parseBindView(Element element, Map<TypeElement, BindingSet.Builder> builderMap,
    Set<TypeElement> erasedTargetNames) {
  TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();

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

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

  if (hasError) {
    return;
  }

  // Assemble information on the field.
  int id = element.getAnnotation(BindView.class).value();

  BindingSet.Builder builder = builderMap.get(enclosingElement);
  QualifiedId qualifiedId = elementToQualifiedId(element, id);
  if (builder != null) {
    String existingBindingName = builder.findExistingBindingName(getId(qualifiedId));
    if (existingBindingName != null) {
      error(element, "Attempt to use @%s for an already bound ID %d on '%s'. (%s.%s)",
          BindView.class.getSimpleName(), id, existingBindingName,
          enclosingElement.getQualifiedName(), element.getSimpleName());
      return;
    }
  } else {
    builder = getOrCreateBindingBuilder(builderMap, enclosingElement);
  }

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

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

  // Add the type-erased version to the valid binding targets set.
  erasedTargetNames.add(enclosingElement);
}
 
Example 11
Project: GitHub   File: PresenterBinderClassGenerator.java   View Source Code Vote up 4 votes
private static String generatePresenterBinderClass(final String builder, String targetClass, final Field field) {
	TypeElement clazz = (TypeElement) ((DeclaredType) field.getClazz()).asElement();
	String s = "\tpublic class " + field.getGeneratedClassName() + " extends PresenterField {\n" +
	           "\t\tpublic " + field.getGeneratedClassName() + "() {\n" +
	           "\t\t\tsuper(" + field.getTag() + ", PresenterType." + field.getType().name() + ", " + field.getPresenterId() + ", " + clazz + ".class);\n" +
	           "\t\t}\n" +
	           "\n" +
	           "\t\[email protected]\n" +
	           "\t\tpublic void bind(Object target, MvpPresenter presenter) {\n" +
	           "\t\t\t((" + targetClass + ") target)." + field.getName() + " = (" + clazz.getQualifiedName() + ") presenter;\n" +
	           "\t\t}\n";

		s += "\n" +
		     "\t\[email protected]\n" +
		     "\t\tpublic MvpPresenter<?> providePresenter(Object delegated) {\n";
	if (field.getPresenterProviderMethodName() != null) {
		s+= "\t\t\treturn ((" + targetClass + ") delegated)." + field.getPresenterProviderMethodName() + "();\n";
	} else {
		boolean hasEmptyConstructor = false;
		List<? extends Element> enclosedElements = clazz.getEnclosedElements();
		for (Element enclosedElement : enclosedElements) {
			if (enclosedElement.getKind() == ElementKind.CONSTRUCTOR) {
				List<? extends VariableElement> parameters = ((ExecutableElement) enclosedElement).getParameters();
				if (parameters == null || parameters.isEmpty()) {
					hasEmptyConstructor = true;
					break;
				}
			}
		}
		if (hasEmptyConstructor) {
		s += "\t\t\treturn new " + clazz.getQualifiedName() + "();\n";
		} else {
		s += "\t\t\tthrow new IllegalStateException(\"" + clazz.getSimpleName() + " has not default constructor. You can apply @ProvidePresenter to some method which will construct Presenter. Also you can make it default constructor\");\n";
		}
	}
	    s += "\t\t}\n";

	if (field.getPresenterTagProviderMethodName() != null) {
		s += "\n" +
		     "\t\[email protected]\n" +
		     "\t\tpublic String getTag(Object delegated) {\n" +
		     "\t\t\treturn String.valueOf(((" + targetClass + ") delegated)." + field.getPresenterTagProviderMethodName() + "());\n" +
		     "\t\t}\n";
	}

	s += "\t}\n" +
	     "\n";
	return builder + s;
}
 
Example 12
Project: GitHub   File: CachingElements.java   View Source Code Vote up 4 votes
CachingTypeElement(TypeElement delegate) {
  super(delegate);
  this.delegate = delegate;
  this.qualifiedName = delegate.getQualifiedName();
}
 
Example 13
Project: Alligator   File: RegistrationAnnotatedClassCreator.java   View Source Code Vote up 4 votes
private void checkThatIsPublic(TypeElement classElement) throws ProcessingException {
	if (!classElement.getModifiers().contains(Modifier.PUBLIC)) {
		throw new ProcessingException(classElement, "The class %s is not public.", classElement.getQualifiedName());
	}
}
 
Example 14
Project: incubator-netbeans   File: JpaControllerUtil.java   View Source Code Vote up 4 votes
public static String getAnnotationQualifiedName(AnnotationMirror annotationMirror) {
    DeclaredType annotationDeclaredType = annotationMirror.getAnnotationType();
    TypeElement annotationTypeElement = (TypeElement) annotationDeclaredType.asElement();
    Name name = annotationTypeElement.getQualifiedName();
    return name.toString();
}
 
Example 15
Project: openjdk-jdk10   File: HtmlDocletWriter.java   View Source Code Vote up 4 votes
public Content interfaceName(TypeElement typeElement, boolean qual) {
    Content name = new StringContent((qual)
            ? typeElement.getQualifiedName()
            : utils.getSimpleName(typeElement));
    return (utils.isInterface(typeElement)) ?  HtmlTree.SPAN(HtmlStyle.interfaceName, name) : name;
}
 
Example 16
Project: react4j   File: ReactProcessor.java   View Source Code Vote up 4 votes
@Nonnull
private EventHandlerDescriptor createEventHandlerDescriptor( @Nonnull final ComponentDescriptor descriptor,
                                                             @Nonnull final ExecutableElement method )
{
  final String name = deriveEventHandlerName( method );
  final TypeElement eventHandlerType = getEventHandlerType( method );
  final ExecutableType methodType =
    (ExecutableType) processingEnv.getTypeUtils().asMemberOf( descriptor.getDeclaredType(), method );
  final List<ExecutableElement> eventHandlerMethods =
    ProcessorUtil.getMethods( eventHandlerType, processingEnv.getTypeUtils() ).stream().
      filter( m11 -> m11.getModifiers().contains( Modifier.ABSTRACT ) ).
      collect( Collectors.toList() );
  if ( eventHandlerMethods.isEmpty() )
  {
    throw new ReactProcessorException( "Method annotated with @EventHandler specified type " +
                                       eventHandlerType.getQualifiedName() + " that has no abstract method and " +
                                       "thus is not a functional interface", method );
  }
  else if ( eventHandlerMethods.size() > 1 )
  {
    throw new ReactProcessorException( "Method annotated with @EventHandler specified type " +
                                       eventHandlerType.getQualifiedName() + " that has more than 1 abstract " +
                                       "method and thus is not a functional interface", method );
  }

  if ( descriptor.isArezComponent() )
  {
    final AnnotationMirror nonActionAnnotation = method.getAnnotationMirrors().stream().
      filter( m -> m.getAnnotationType().toString().equals( "react4j.arez.NoAutoAction" ) ).
      findAny().orElse( null );
    if ( null == nonActionAnnotation )
    {
      final AnnotationMirror actionAnnotation = method.getAnnotationMirrors().stream().
        filter( m -> m.getAnnotationType().toString().equals( "arez.annotations.Action" ) ).
        findAny().orElse( null );
      if ( null != actionAnnotation )
      {
        throw new ReactProcessorException( "Method annotated with @EventHandler is also annotated with " +
                                           "@arez.annotations.Action but is not annotated with " +
                                           "@react4j.arez.NoAutoAction which would stop react4j from also " +
                                           "annotating the method with @Action. Please remove @Action or add " +
                                           "@NoAutoAction annotation.", method );
      }
    }
  }

  return new EventHandlerDescriptor( name, method, methodType, eventHandlerType, eventHandlerMethods.get( 0 ) );
}
 
Example 17
Project: alvisnlp   File: ModelContext.java   View Source Code Vote up 4 votes
String getModuleDataClass(TypeElement moduleElement) throws ModelException {
	if (isCorpusModule(moduleElement))
		return Corpus.class.getCanonicalName();
	throw new ModelException("cannot determine model for module: " + moduleElement.getQualifiedName());
}
 
Example 18
Project: butterknife-parent   File: ButterKnifeProcessor.java   View Source Code Vote up 4 votes
private void parseBindView(Element element, Map<TypeElement, BindingSet.Builder> builderMap,
      Set<TypeElement> erasedTargetNames) {
    TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();

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

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

    if (hasError) {
      return;
    }

    // Assemble information on the field.
    int id = element.getAnnotation(BindView.class).value();
    int parentId = element.getAnnotation(BindView.class).parentId();

    BindingSet.Builder builder = builderMap.get(enclosingElement);
    QualifiedId qualifiedId = elementToQualifiedId(element, id);
    if (builder != null) {
//      String existingBindingName = builder.findExistingBindingName(getId(qualifiedId));
//      if (existingBindingName != null) {
//        error(element, "Attempt to use @%s for an already bound ID %d on '%s'. (%s.%s)",
//            BindView.class.getSimpleName(), id, existingBindingName,
//            enclosingElement.getQualifiedName(), element.getSimpleName());
//        return;
//      }
    } else {
      builder = createBindingBuilder(builderMap, enclosingElement);
    }

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

    builder.addField(getId(qualifiedId), new FieldViewBinding(name, type, required, parentId));

    // Add the type-erased version to the valid binding targets set.
    erasedTargetNames.add(enclosingElement);
  }
 
Example 19
Project: OpenJSharp   File: Gen.java   View Source Code Vote up 4 votes
protected String defineForStatic(TypeElement c, VariableElement f)
        throws Util.Exit {
    CharSequence cnamedoc = c.getQualifiedName();
    CharSequence fnamedoc = f.getSimpleName();

    String cname = mangler.mangle(cnamedoc, Mangle.Type.CLASS);
    String fname = mangler.mangle(fnamedoc, Mangle.Type.FIELDSTUB);

    if (!f.getModifiers().contains(Modifier.STATIC))
        util.bug("tried.to.define.non.static");

    if (f.getModifiers().contains(Modifier.FINAL)) {
        Object value = null;

        value = f.getConstantValue();

        if (value != null) { /* so it is a ConstantExpression */
            String constString = null;
            if ((value instanceof Integer)
                || (value instanceof Byte)
                || (value instanceof Short)) {
                /* covers byte, short, int */
                constString = value.toString() + "L";
            } else if (value instanceof Boolean) {
                constString = ((Boolean) value) ? "1L" : "0L";
            } else if (value instanceof Character) {
                Character ch = (Character) value;
                constString = String.valueOf(((int) ch) & 0xffff) + "L";
            } else if (value instanceof Long) {
                // Visual C++ supports the i64 suffix, not LL.
                if (isWindows)
                    constString = value.toString() + "i64";
                else
                    constString = value.toString() + "LL";
            } else if (value instanceof Float) {
                /* bug for bug */
                float fv = ((Float)value).floatValue();
                if (Float.isInfinite(fv))
                    constString = ((fv < 0) ? "-" : "") + "Inff";
                else
                    constString = value.toString() + "f";
            } else if (value instanceof Double) {
                /* bug for bug */
                double d = ((Double)value).doubleValue();
                if (Double.isInfinite(d))
                    constString = ((d < 0) ? "-" : "") + "InfD";
                else
                    constString = value.toString();
            }
            if (constString != null) {
                StringBuilder s = new StringBuilder("#undef ");
                s.append(cname); s.append("_"); s.append(fname); s.append(lineSep);
                s.append("#define "); s.append(cname); s.append("_");
                s.append(fname); s.append(" "); s.append(constString);
                return s.toString();
            }

        }
    }
    return null;
}
 
Example 20
Project: openjdk-jdk10   File: Gen.java   View Source Code Vote up 4 votes
protected String defineForStatic(TypeElement c, VariableElement f)
        throws Util.Exit {
    CharSequence cnamedoc = c.getQualifiedName();
    CharSequence fnamedoc = f.getSimpleName();

    String cname = mangler.mangle(cnamedoc, Mangle.Type.CLASS);
    String fname = mangler.mangle(fnamedoc, Mangle.Type.FIELDSTUB);

    if (!f.getModifiers().contains(Modifier.STATIC))
        util.bug("tried.to.define.non.static");

    if (f.getModifiers().contains(Modifier.FINAL)) {
        Object value = null;

        value = f.getConstantValue();

        if (value != null) { /* so it is a ConstantExpression */
            String constString = null;
            if ((value instanceof Integer)
                || (value instanceof Byte)
                || (value instanceof Short)) {
                /* covers byte, short, int */
                constString = value.toString() + "L";
            } else if (value instanceof Boolean) {
                constString = ((Boolean) value) ? "1L" : "0L";
            } else if (value instanceof Character) {
                Character ch = (Character) value;
                constString = String.valueOf(((int) ch) & 0xffff) + "L";
            } else if (value instanceof Long) {
                // Visual C++ supports the i64 suffix, not LL.
                if (isWindows)
                    constString = value.toString() + "i64";
                else
                    constString = value.toString() + "LL";
            } else if (value instanceof Float) {
                /* bug for bug */
                float fv = ((Float)value).floatValue();
                if (Float.isInfinite(fv))
                    constString = ((fv < 0) ? "-" : "") + "Inff";
                else
                    constString = value.toString() + "f";
            } else if (value instanceof Double) {
                /* bug for bug */
                double d = ((Double)value).doubleValue();
                if (Double.isInfinite(d))
                    constString = ((d < 0) ? "-" : "") + "InfD";
                else
                    constString = value.toString();
            }
            if (constString != null) {
                StringBuilder s = new StringBuilder("#undef ");
                s.append(cname); s.append("_"); s.append(fname); s.append(lineSep);
                s.append("#define "); s.append(cname); s.append("_");
                s.append(fname); s.append(" "); s.append(constString);
                return s.toString();
            }

        }
    }
    return null;
}