当前位置: 首页>>代码示例>>Java>>正文


Java Types.asElement方法代码示例

本文整理汇总了Java中javax.lang.model.util.Types.asElement方法的典型用法代码示例。如果您正苦于以下问题:Java Types.asElement方法的具体用法?Java Types.asElement怎么用?Java Types.asElement使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在javax.lang.model.util.Types的用法示例。


在下文中一共展示了Types.asElement方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: stripCollection

import javax.lang.model.util.Types; //导入方法依赖的package包/类
public static TypeMirror stripCollection(TypeMirror passedType, Types types) {
    if (TypeKind.DECLARED != passedType.getKind() || !(passedType instanceof DeclaredType)) {
        return passedType;
    }
    TypeElement passedTypeElement = (TypeElement) types.asElement(passedType);
    String passedTypeQualifiedName = passedTypeElement.getQualifiedName().toString();   //does not include type parameter info
    Class passedTypeClass = null;
    try {
        passedTypeClass = Class.forName(passedTypeQualifiedName);
    } catch (ClassNotFoundException e) {
        //just let passedTypeClass be null
    }
    if (passedTypeClass != null && Collection.class.isAssignableFrom(passedTypeClass)) {
        List<? extends TypeMirror> passedTypeArgs = ((DeclaredType)passedType).getTypeArguments();
        if (passedTypeArgs.isEmpty()) {
            return passedType;
        }
        return passedTypeArgs.get(0);
    }
    return passedType;
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:22,代码来源:JpaControllerUtil.java

示例2: getJavadocSafeName

import javax.lang.model.util.Types; //导入方法依赖的package包/类
/**
 * Returns a safe String to use in a Javadoc that will function in a link.
 *
 * <p>This method exists because by Javadoc doesn't handle type parameters({@literal <T>}
 * in {@literal RequestOptions<T>} for example).
 */
private TypeName getJavadocSafeName(Element element) {
  Types typeUtils = processingEnv.getTypeUtils();
  TypeMirror type = element.asType();
  if (typeUtils.asElement(type) == null) {
    // If there is no Element, it's a primitive and can't have additional types, so we're done.
    return ClassName.get(element.asType());
  }
  Name simpleName = typeUtils.asElement(type).getSimpleName();
  return ClassName.bestGuess(simpleName.toString());
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:17,代码来源:ProcessorUtil.java

示例3: getAnnotationValueClassName

import javax.lang.model.util.Types; //导入方法依赖的package包/类
/**
 * Returns fully qualified class name of a class given to an annotation
 * as (the only) argument.
 * 
 * @param  annValue  annotation value
 * @return  fully qualified name of a class represented by the given
 *          annotation value, or {@code null} if the annotation value
 *          does not represent a class
 */
private Name getAnnotationValueClassName(AnnotationValue annValue,
                                         Types types) {
    Object value = annValue.getValue();
    if (value instanceof TypeMirror) {
        TypeMirror typeMirror = (TypeMirror) value;
        Element typeElement = types.asElement(typeMirror);
        if (typeElement.getKind() == ElementKind.CLASS) {
            return ((TypeElement) typeElement).getQualifiedName();
        }
    }
    return null;
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:22,代码来源:TestGenerator.java

示例4: tryToExtractClassName

import javax.lang.model.util.Types; //导入方法依赖的package包/类
public static String tryToExtractClassName(Types typeUtils, Element element) {
    TypeElement typeElement = (TypeElement) typeUtils.asElement(element.asType());
    // TODO - consider consequences if annotated field is a generic
    return typeElement == null
            ? element.getSimpleName().toString()
            : typeElement.getSimpleName().toString();
}
 
开发者ID:jzallas,项目名称:LifecycleAware,代码行数:8,代码来源:Utils.java

示例5: getSuperElement

import javax.lang.model.util.Types; //导入方法依赖的package包/类
public static TypeElement getSuperElement(Types types,Element element){
	if (element instanceof TypeElement){
		TypeElement typeElement = (TypeElement) element;
		Element superElement = types.asElement(typeElement.getSuperclass());
		return (TypeElement) superElement;
	}
	return null;
}
 
开发者ID:tik5213,项目名称:DUnit,代码行数:9,代码来源:ElementUtil.java

示例6: findImports

import javax.lang.model.util.Types; //导入方法依赖的package包/类
/**
 * Given a set of referenced types, works out which of them should be imported and what the
 * resulting spelling of each one is.
 *
 * <p>This method operates on a {@code Set<TypeMirror>} rather than just a {@code Set<String>}
 * because it is not strictly possible to determine what part of a fully-qualified type name is
 * the package and what part is the top-level class. For example, {@code java.util.Map.Entry} is
 * a class called {@code Map.Entry} in a package called {@code java.util} assuming Java
 * conventions are being followed, but it could theoretically also be a class called {@code Entry}
 * in a package called {@code java.util.Map}. Since we are operating as part of the compiler, our
 * goal should be complete correctness, and the only way to achieve that is to operate on the real
 * representations of types.
 *
 * @param packageName The name of the package where the class containing these references is
 *     defined. Other classes within the same package do not need to be imported.
 * @param referenced The complete set of declared types (classes and interfaces) that will be
 *     referenced in the generated code.
 * @param defined The complete set of declared types (classes and interfaces) that are defined
 *     within the scope of the generated class (i.e. nested somewhere in its superclass chain,
 *     or in its interface set)
 * @return a map where the keys are fully-qualified types and the corresponding values indicate
 *     whether the type should be imported, and how the type should be spelled in the source code.
 */
private static Map<String, Spelling> findImports(
        Types typeUtils, String packageName, Set<TypeMirror> referenced, Set<TypeMirror> defined) {
    Map<String, Spelling> imports = new HashMap<String, Spelling>();
    Set<TypeMirror> typesInScope = new TypeMirrorSet();
    typesInScope.addAll(referenced);
    typesInScope.addAll(defined);
    Set<String> ambiguous = ambiguousNames(typeUtils, typesInScope);
    for (TypeMirror type : referenced) {
        TypeElement typeElement = (TypeElement) typeUtils.asElement(type);
        String fullName = typeElement.getQualifiedName().toString();
        String simpleName = typeElement.getSimpleName().toString();
        String pkg = packageNameOf(typeElement);
        boolean importIt;
        String spelling;
        if (ambiguous.contains(simpleName)) {
            importIt = false;
            spelling = fullName;
        } else if (pkg.equals(packageName) || pkg.equals("java.lang")) {
            importIt = false;
            spelling = fullName.substring(pkg.isEmpty() ? 0 : pkg.length() + 1);
        } else {
            importIt = true;
            spelling = simpleName;
        }
        imports.put(fullName, new Spelling(spelling, importIt));
    }
    return imports;
}
 
开发者ID:ccheptea,项目名称:auto-value-node,代码行数:52,代码来源:TypeSimplifier.java

示例7: isIterable

import javax.lang.model.util.Types; //导入方法依赖的package包/类
public static boolean isIterable(Element element, Types typeUtils) {
    if (isPrimitiveOrWrapper(element.asType())) {
        return false;
    }
    TypeElement typeElement = (TypeElement) typeUtils.asElement(element.asType());

    return isIterable(typeElement);
}
 
开发者ID:foodora,项目名称:android-auto-mapper,代码行数:9,代码来源:TypeUtil.java

示例8: addNonPrivateFields

import javax.lang.model.util.Types; //导入方法依赖的package包/类
private void addNonPrivateFields(TypeElement element, List<VariableElement> nonPrivateFields) {
    if (hasSuperClass(element)) {
        Types typeUtils = processingEnv.getTypeUtils();
        Element elm = typeUtils.asElement(element.getSuperclass());
        addNonPrivateFields((TypeElement) elm, nonPrivateFields);
    }
    nonPrivateFields.addAll(getParcelableFieldsOrError(element));
}
 
开发者ID:foodora,项目名称:android-auto-mapper,代码行数:9,代码来源:AutoMappperProcessor.java

示例9: findImports

import javax.lang.model.util.Types; //导入方法依赖的package包/类
/**
 * Given a set of referenced types, works out which of them should be imported and what the
 * resulting spelling of each one is.
 *
 * <p>This method operates on a {@code Set<TypeMirror>} rather than just a {@code Set<String>}
 * because it is not strictly possible to determine what part of a fully-qualified type name is
 * the package and what part is the top-level class. For example, {@code java.util.Map.Entry} is
 * a class called {@code Map.Entry} in a package called {@code java.util} assuming Java
 * conventions are being followed, but it could theoretically also be a class called {@code Entry}
 * in a package called {@code java.util.Map}. Since we are operating as part of the compiler, our
 * goal should be complete correctness, and the only way to achieve that is to operate on the real
 * representations of types.
 *
 * @param packageName The name of the package where the class containing these references is
 *     defined. Other classes within the same package do not need to be imported.
 * @param referenced The complete set of declared types (classes and interfaces) that will be
 *     referenced in the generated code.
 * @param defined The complete set of declared types (classes and interfaces) that are defined
 *     within the scope of the generated class (i.e. nested somewhere in its superclass chain,
 *     or in its interface set)
 * @return a map where the keys are fully-qualified types and the corresponding values indicate
 *     whether the type should be imported, and how the type should be spelled in the source code.
 */
private static Map<String, Spelling> findImports(
    Types typeUtils, String packageName, Set<TypeMirror> referenced, Set<TypeMirror> defined) {
  Map<String, Spelling> imports = new HashMap<String, Spelling>();
  Set<TypeMirror> typesInScope = new TypeMirrorSet();
  typesInScope.addAll(referenced);
  typesInScope.addAll(defined);
  Set<String> ambiguous = ambiguousNames(typeUtils, typesInScope);
  for (TypeMirror type : referenced) {
    TypeElement typeElement = (TypeElement) typeUtils.asElement(type);
    String fullName = typeElement.getQualifiedName().toString();
    String simpleName = typeElement.getSimpleName().toString();
    String pkg = packageNameOf(typeElement);
    boolean importIt;
    String spelling;
    if (ambiguous.contains(simpleName)) {
      importIt = false;
      spelling = fullName;
    } else if (pkg.equals(packageName) || pkg.equals("java.lang")) {
      importIt = false;
      spelling = fullName.substring(pkg.isEmpty() ? 0 : pkg.length() + 1);
    } else {
      importIt = true;
      spelling = simpleName;
    }
    imports.put(fullName, new Spelling(spelling, importIt));
  }
  return imports;
}
 
开发者ID:sopak,项目名称:auto-value-step-builder,代码行数:52,代码来源:TypeSimplifier.java

示例10: getOtherSideOfRelation

import javax.lang.model.util.Types; //导入方法依赖的package包/类
public static ExecutableElement getOtherSideOfRelation(CompilationController controller, ExecutableElement executableElement, boolean isFieldAccess) {
    TypeMirror passedReturnType = executableElement.getReturnType();
    if (TypeKind.DECLARED != passedReturnType.getKind() || !(passedReturnType instanceof DeclaredType)) {
        return null;
    }
    Types types = controller.getTypes();
    TypeMirror passedReturnTypeStripped = stripCollection((DeclaredType)passedReturnType, types);
    if (passedReturnTypeStripped == null) {
        return null;
    }
    TypeElement passedReturnTypeStrippedElement = (TypeElement) types.asElement(passedReturnTypeStripped);
    
    //try to find a mappedBy annotation element on the possiblyAnnotatedElement
    Element possiblyAnnotatedElement = isFieldAccess ? JpaControllerUtil.guessField(executableElement) : executableElement;
    String mappedBy = null;
    AnnotationMirror persistenceAnnotation = JpaControllerUtil.findAnnotation(possiblyAnnotatedElement, "javax.persistence.OneToOne");  //NOI18N"
    if (persistenceAnnotation == null) {
        persistenceAnnotation = JpaControllerUtil.findAnnotation(possiblyAnnotatedElement, "javax.persistence.OneToMany");  //NOI18N"
    }
    if (persistenceAnnotation == null) {
        persistenceAnnotation = JpaControllerUtil.findAnnotation(possiblyAnnotatedElement, "javax.persistence.ManyToOne");  //NOI18N"
    }
    if (persistenceAnnotation == null) {
        persistenceAnnotation = JpaControllerUtil.findAnnotation(possiblyAnnotatedElement, "javax.persistence.ManyToMany");  //NOI18N"
    }
    if (persistenceAnnotation != null) {
        mappedBy = JpaControllerUtil.findAnnotationValueAsString(persistenceAnnotation, "mappedBy");  //NOI18N
    }
    for (ExecutableElement method : JpaControllerUtil.getEntityMethods(passedReturnTypeStrippedElement)) {
        if (mappedBy != null && mappedBy.length() > 0) {
            String tail = mappedBy.length() > 1 ? mappedBy.substring(1) : "";
            String getterName = "get" + mappedBy.substring(0,1).toUpperCase() + tail;
            if (getterName.equals(method.getSimpleName().toString())) {
                return method;
            }
        }
        else {
            TypeMirror iteratedReturnType = method.getReturnType();
            iteratedReturnType = stripCollection(iteratedReturnType, types);
            TypeMirror executableElementEnclosingType = executableElement.getEnclosingElement().asType();
            if (types.isSameType(executableElementEnclosingType, iteratedReturnType)) {
                return method;
            }
        }
    }
    return null;
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:48,代码来源:JpaControllerUtil.java

示例11: fixGenericTypes

import javax.lang.model.util.Types; //导入方法依赖的package包/类
private <E extends Tree> E fixGenericTypes(E tree, final TreePath path, final Element member) {
    final Map<TypeMirror, TypeParameterElement> mappings = new HashMap<TypeMirror, TypeParameterElement>();
    DeclaredType declaredType = (DeclaredType) sourceType.asType();
    for (TypeMirror typeMirror : declaredType.getTypeArguments()) {
        DeclaredType currentElement = declaredType;
        deepSearchTypes(currentElement, typeMirror, typeMirror, mappings);
    }
    final Types types = workingCopy.getTypes();

    final Map<IdentifierTree, Tree> original2Translated = new HashMap<IdentifierTree, Tree>();
    ErrorAwareTreeScanner<Void, Void> scanner = new ErrorAwareTreeScanner<Void, Void>() {

        @Override
        public Void visitIdentifier(IdentifierTree node, Void p) {
            Element element = workingCopy.getTrees().getElement(new TreePath(path, node));
            if (element != null && element.getKind() == ElementKind.TYPE_PARAMETER) {
                Element typeElement = types.asElement(element.asType());
                if (typeElement != null && typeElement.getKind() == ElementKind.TYPE_PARAMETER) {
                    TypeParameterElement parameterElement = (TypeParameterElement) typeElement;
                    Element genericElement = parameterElement.getGenericElement();
                    if (genericElement != member) {
                        // genericElement is niet gelijk aan het te verplaatsen element. Dus we moeten deze veranderen.
                        // Is het parameterElement gebruikt bij het maken van de superclass

                        Tree type;
                        TypeParameterElement target = mappings.get(parameterElement.asType());
                        if (target != null) {
                            type = make.Type(target.asType());
                        } else {
                            List<? extends TypeMirror> bounds = parameterElement.getBounds();
                            if (bounds.isEmpty()) {
                                type = make.Type("Object"); // NOI18N
                            } else {
                                type = make.Type(bounds.get(0));
                            }
                        }
                        original2Translated.put(node, type);
                    }
                }
            }
            return super.visitIdentifier(node, p);
        }
    };
    scanner.scan(tree, null);
    E result = (E) workingCopy.getTreeUtilities().translate(tree, original2Translated);
    return result;
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:48,代码来源:PullUpTransformer.java

示例12: initCause

import javax.lang.model.util.Types; //导入方法依赖的package包/类
private static ErrorDescription initCause(HintContext ctx, boolean toThrow) {
    TypeElement throwable = ctx.getInfo().getElements().getTypeElement("java.lang.Throwable");

    if (throwable == null) return null;

    TreePath exc = ctx.getVariables().get("$exc");
    TypeMirror excType = ctx.getInfo().getTrees().getTypeMirror(exc);
    Types t = ctx.getInfo().getTypes();

    if (!t.isSubtype(t.erasure(excType), t.erasure(throwable.asType()))) {
        return null;
    }

    Element el = t.asElement(excType);

    if (el == null || el.getKind() != ElementKind.CLASS) {
        //should not happen
        return null;
    }

    List<TypeMirror> constrParams = new LinkedList<TypeMirror>();
    TreePath str = ctx.getVariables().get("$str");
    String target;

    if (   (str != null && (   MatcherUtilities.matches(ctx, str, "$del.toString()")
                            || (    MatcherUtilities.matches(ctx, str, "$del.getMessage()")
                                && !ctx.getPreferences().getBoolean(STRICT_KEY, STRICT_DEFAULT))
                            || (    MatcherUtilities.matches(ctx, str, "$del.getLocalizedMessage()")
                                && !ctx.getPreferences().getBoolean(STRICT_KEY, STRICT_DEFAULT)))
        || (str == null && !ctx.getPreferences().getBoolean(STRICT_KEY, STRICT_DEFAULT)))) {
        target = "new $exc($del)";
    } else {
        TypeElement jlString = ctx.getInfo().getElements().getTypeElement("java.lang.String");

        if (jlString == null) return null;

        constrParams.add(jlString.asType());

        if (str != null) {
            target = "new $exc($str, $del)";
        } else {
            target = "new $exc(null, $del)"; //TODO: might lead to incompilable code (for overloaded constructors)
        }
    }

    if (toThrow) {
        target = "throw " + target + ";";
    }

    TreePath del = ctx.getVariables().get("$del");
    TypeMirror delType = ctx.getInfo().getTrees().getTypeMirror(del);

    constrParams.add(delType);

    if (!findConstructor(el, t, constrParams)) return null;

    String fixDisplayName = NbBundle.getMessage(ThrowableInitCause.class, "FIX_ThrowableInitCause");
    String displayName = NbBundle.getMessage(ThrowableInitCause.class, "ERR_ThrowableInitCause");
    TreePath toUnderline = ctx.getVariables().get("$excVar");

    if (toUnderline == null) {
        toUnderline = ctx.getPath();
    }

    return ErrorDescriptionFactory.forTree(ctx, toUnderline, displayName, JavaFixUtilities.rewriteFix(ctx, fixDisplayName, ctx.getPath(), target));
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:67,代码来源:ThrowableInitCause.java


注:本文中的javax.lang.model.util.Types.asElement方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。