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

The following are Jave code examples for showing how to use asType() 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.
Example 1
Project: GitHub   File: PresenterInjectorRules.java   Source Code and License Vote up 6 votes
private Collection<TypeMirror> getViewsType(TypeElement typeElement) {
	TypeMirror superclass = typeElement.asType();

	List<TypeMirror> result = new ArrayList<>();

	while (superclass.getKind() != TypeKind.NONE) {
		TypeElement superclassElement = (TypeElement) ((DeclaredType) superclass).asElement();
		Collection<? extends TypeMirror> interfaces = new HashSet<>(superclassElement.getInterfaces());
		for (TypeMirror typeMirror : interfaces) {
			if (typeMirror instanceof DeclaredType) {
				result.addAll(getViewsType((TypeElement) ((DeclaredType) typeMirror).asElement()));
			}
		}
		result.addAll(interfaces);
		result.add(superclass);

		superclass = superclassElement.getSuperclass();
	}

	return result;
}
 
Example 2
Project: incubator-netbeans   File: WatchPanel.java   Source Code and License Vote up 6 votes
@Override
public TypeMirror getTypeMirror(TreePath arg0) {
    Tree tree = arg0.getLeaf();
    if (tree.getKind() == Tree.Kind.IDENTIFIER) {
        Map<String, ObjectVariable> map = null;
        try {
            // [TODO] add JPDADebuggerImpl.getAllLabels() to API
            Method method = debugger.getClass().getMethod("getAllLabels"); // NOI18N
            map = (Map<String, ObjectVariable>) method.invoke(debugger);
        } catch (Exception ex) {
            Exceptions.printStackTrace(ex);
        }
        if (map != null) {
            String name = ((IdentifierTree)tree).getName().toString();
            ObjectVariable var = map.get(name);
            if (var != null) {
                Elements elements = controller.getElements();
                TypeElement typeElem = elements.getTypeElement(var.getClassType().getName());
                if (typeElem != null) {
                    return typeElem.asType();
                }
            }
        }
    }
    return trees.getTypeMirror(arg0);
}
 
Example 3
Project: incubator-netbeans   File: TypeUtilities.java   Source Code and License Vote up 6 votes
private static TypeMirror resolveCapturedType(CompilationInfo info, TypeMirror tm) {
    if (tm == null) {
        return tm;
    }
    if (tm.getKind() == TypeKind.ERROR) {
        tm = info.getTrees().getOriginalType((ErrorType) tm);
    }
    TypeMirror type = resolveCapturedTypeInt(info, tm);
    if (type == null) {
        return tm;
    }
    if (type.getKind() == TypeKind.WILDCARD) {
        TypeMirror tmirr = ((WildcardType) type).getExtendsBound();
        if (tmirr != null)
            return tmirr;
        else { //no extends, just '?'
            TypeElement te = info.getElements().getTypeElement("java.lang.Object"); // NOI18N
            return te == null ? null : te.asType();
        }
            
    }
    
    return type;
}
 
Example 4
Project: incubator-netbeans   File: Flow.java   Source Code and License Vote up 6 votes
public VisitorImpl(CompilationInfo info, TypeElement undefinedSymbolScope, Cancel cancel) {
    super();
    this.info = info;
    this.cancel = cancel;
    this.undefinedSymbolScope = undefinedSymbolScope;
    this.thisName = info.getElements().getName("this");

    this.throwableEl = info.getElements().getTypeElement("java.lang.Throwable"); // NOI18N
    TypeElement tel =  info.getElements().getTypeElement("java.lang.RuntimeException"); // NOI18N
    if (tel != null) {
        runtimeExceptionType = tel.asType();
    } else {
        runtimeExceptionType = null;
    }
    tel =  info.getElements().getTypeElement("java.lang.Error"); // NOI18N
    if (tel != null) {
        errorType = tel.asType();
    } else {
        errorType = null;
    }
}
 
Example 5
Project: incubator-netbeans   File: Utilities.java   Source Code and License Vote up 6 votes
public static TypeMirror resolveCapturedType(CompilationInfo info, TypeMirror tm) {
    if (tm == null) {
        return tm;
    }
    if (tm.getKind() == TypeKind.ERROR) {
        tm = info.getTrees().getOriginalType((ErrorType) tm);
    }
    TypeMirror type = resolveCapturedTypeInt(info, tm);
    if (type == null) {
        return tm;
    }
    if (type.getKind() == TypeKind.WILDCARD) {
        TypeMirror tmirr = ((WildcardType) type).getExtendsBound();
        if (tmirr != null)
            return tmirr;
        else { //no extends, just '?'
            TypeElement te = info.getElements().getTypeElement("java.lang.Object"); // NOI18N
            return te == null ? null : te.asType();
        }
            
    }
    
    return type;
}
 
Example 6
Project: incubator-netbeans   File: CreateEnumConstant.java   Source Code and License Vote up 6 votes
public CreateEnumConstant(CompilationInfo info, String name, Set<Modifier> modifiers, TypeElement target, TypeMirror proposedType, FileObject targetFile) {
    this.name = name;
    this.inFQN = target.getQualifiedName().toString();
    this.cpInfo = info.getClasspathInfo();
    this.targetFile = targetFile;
    this.target = ElementHandle.create(target);
    if (proposedType.getKind() == TypeKind.NULL) {
        TypeElement tel = info.getElements().getTypeElement("java.lang.Object"); // NOI18N
        if (tel != null) {
            proposedType = tel.asType();
            this.proposedType = TypeMirrorHandle.create(proposedType);
        } else {
            this.proposedType = null;
        }
    } else {
        this.proposedType = TypeMirrorHandle.create(proposedType);
    }
}
 
Example 7
Project: incubator-netbeans   File: Analyzer.java   Source Code and License Vote up 5 votes
@NbBundle.Messages({"# {0} - [@throws|@exception]", "# {1} - @throws name",
                    "DUPLICATE_THROWS_DESC=Duplicate @{0} tag: {1}",
                    "# {0} - [@throws|@exception]", "# {1} - @throws name",
                    "UNKNOWN_THROWABLE_DESC=Unknown throwable: @{0} {1}"})
private void checkThrowsDeclared(ThrowsTree tree, Element ex, String fqn, List<? extends TypeMirror> list, DocTreePathHandle dtph, int start, int end, List<ErrorDescription> errors) {
    boolean found = false;
    final TypeMirror type;
    if(ex != null) {
        type = ex.asType();
    } else {
        TypeElement typeElement = javac.getElements().getTypeElement(fqn);
        if(typeElement != null) {
            type = typeElement.asType();
        } else {
            type = null;
        }
    }
    for (TypeMirror t: list) {
        if(ctx.isCanceled()) { return; }
        if(type != null && javac.getTypes().isAssignable(type, t)) {
            if(!foundThrows.add(type)) {
                errors.add(ErrorDescriptionFactory.forSpan(ctx, start, end, DUPLICATE_THROWS_DESC(tree.getTagName(), fqn), new RemoveTagFix(dtph, "@" + tree.getTagName()).toEditorFix()));
            }
            found = true;
            break;
        }
        if (type == null && fqn.equals(t.toString())) {
            if(!foundThrows.add(t)) {
                errors.add(ErrorDescriptionFactory.forSpan(ctx, start, end, DUPLICATE_THROWS_DESC(tree.getTagName(), fqn), new RemoveTagFix(dtph, "@" + tree.getTagName()).toEditorFix()));
            }
            found = true;
            break;
        }
    }
    if (!found) {
        errors.add(ErrorDescriptionFactory.forSpan(ctx, start, end, UNKNOWN_THROWABLE_DESC(tree.getTagName(), fqn), new RemoveTagFix(dtph, "@" + tree.getTagName()).toEditorFix()));
    }
}
 
Example 8
Project: GitHub   File: ViewStateProviderClassGenerator.java   Source Code and License Vote up 5 votes
private String getViewClassFromGeneric(TypeElement typeElement) {
	TypeMirror superclass = typeElement.asType();

	Map<String, String> parentTypes = Collections.emptyMap();

	if (!typeElement.getTypeParameters().isEmpty()) {
		MvpCompiler.getMessager().printMessage(Diagnostic.Kind.WARNING, "Your " + typeElement.getSimpleName() + " is typed. @InjectViewState may generate wrong code. Your can set view/view state class manually.");
	}

	while (superclass.getKind() != TypeKind.NONE) {
		TypeElement superclassElement = (TypeElement) ((DeclaredType) superclass).asElement();

		final List<? extends TypeMirror> typeArguments = ((DeclaredType) superclass).getTypeArguments();
		final List<? extends TypeParameterElement> typeParameters = superclassElement.getTypeParameters();

		if (typeArguments.size() > typeParameters.size()) {
			throw new IllegalArgumentException("Code generation for interface " + typeElement.getSimpleName() + " failed. Simplify your generics. (" + typeArguments + " vs " + typeParameters + ")");
		}

		Map<String, String> types = new HashMap<>();
		for (int i = 0; i < typeArguments.size(); i++) {
			types.put(typeParameters.get(i).toString(), fillGenerics(parentTypes, typeArguments.get(i)));
		}

		if (superclassElement.toString().equals(MVP_PRESENTER_CLASS)) {
			// MvpPresenter is typed only on View class
			return fillGenerics(parentTypes, typeArguments);
		}

		parentTypes = types;

		superclass = superclassElement.getSuperclass();
	}

	return "";
}
 
Example 9
Project: incubator-netbeans   File: AnnotationHelper.java   Source Code and License Vote up 5 votes
public TypeMirror resolveType(String typeName) {
    TypeElement type = getCompilationInfo().getElements().getTypeElement(typeName);
    if (type != null) {
        return type.asType();
    }
    return null;
}
 
Example 10
Project: openjdk-jdk10   File: Utils.java   Source Code and License Vote up 5 votes
public TypeMirror getSymbol(String signature) {
    TypeMirror type = symtab.get(signature);
    if (type == null) {
        TypeElement typeElement = elementUtils.getTypeElement(signature);
        if (typeElement == null)
            return null;
        type = typeElement.asType();
        if (type == null)
            return null;
        symtab.put(signature, type);
    }
    return type;
}
 
Example 11
Project: incubator-netbeans   File: Utilities.java   Source Code and License Vote up 5 votes
/**
 *
 * @param info context {@link CompilationInfo}
 * @param iterable tested {@link TreePath}
 * @return generic type of an {@link Iterable} or {@link ArrayType} at a TreePath
 */
public static TypeMirror getIterableGenericType(CompilationInfo info, TreePath iterable) {
    TypeElement iterableElement = info.getElements().getTypeElement("java.lang.Iterable"); //NOI18N
    if (iterableElement == null) {
        return null;
    }
    TypeMirror iterableType = info.getTrees().getTypeMirror(iterable);
    if (iterableType == null) {
        return null;
    }
    TypeMirror designedType = null;
    if (iterableType.getKind() == TypeKind.DECLARED) {
        DeclaredType declaredType = (DeclaredType) iterableType;
        if (!info.getTypes().isSubtype(info.getTypes().erasure(declaredType), info.getTypes().erasure(iterableElement.asType()))) {
            return null;
        }
        ExecutableElement iteratorMethod = (ExecutableElement) iterableElement.getEnclosedElements().get(0);
        ExecutableType iteratorMethodType = (ExecutableType) info.getTypes().asMemberOf(declaredType, iteratorMethod);
        List<? extends TypeMirror> typeArguments = ((DeclaredType) iteratorMethodType.getReturnType()).getTypeArguments();
        if (!typeArguments.isEmpty()) {
            designedType = typeArguments.get(0);
        } else {
            TypeElement jlObject = info.getElements().getTypeElement("java.lang.Object");

            if (jlObject != null) {
                designedType = jlObject.asType();
            }
        }
    } else if (iterableType.getKind() == TypeKind.ARRAY) {
        designedType = ((ArrayType) iterableType).getComponentType();
    }
    if (designedType == null) {
        return null;
    }
    return resolveTypeForDeclaration(info, designedType);
}
 
Example 12
Project: incubator-netbeans   File: CreateElementUtilities.java   Source Code and License Vote up 5 votes
/**
 *
 * @param info context {@link CompilationInfo}
 * @param iterable tested {@link TreePath}
 * @return generic type of an {@link Iterable} or {@link ArrayType} at a TreePath
 */
public static TypeMirror getIterableGenericType(CompilationInfo info, TreePath iterable) {
    TypeElement iterableElement = info.getElements().getTypeElement("java.lang.Iterable"); //NOI18N
    if (iterableElement == null) {
        return null;
    }
    TypeMirror iterableType = info.getTrees().getTypeMirror(iterable);
    if (iterableType == null) {
        return null;
    }
    TypeMirror designedType = null;
    if (iterableType.getKind() == TypeKind.DECLARED) {
        DeclaredType declaredType = (DeclaredType) iterableType;
        if (!info.getTypes().isSubtype(info.getTypes().erasure(declaredType), info.getTypes().erasure(iterableElement.asType()))) {
            return null;
        }
        ExecutableElement iteratorMethod = (ExecutableElement) iterableElement.getEnclosedElements().get(0);
        ExecutableType iteratorMethodType = (ExecutableType) info.getTypes().asMemberOf(declaredType, iteratorMethod);
        List<? extends TypeMirror> typeArguments = ((DeclaredType) iteratorMethodType.getReturnType()).getTypeArguments();
        if (!typeArguments.isEmpty()) {
            designedType = typeArguments.get(0);
        } else {
            TypeElement jlObject = info.getElements().getTypeElement("java.lang.Object");

            if (jlObject != null) {
                designedType = jlObject.asType();
            }
        }
    } else if (iterableType.getKind() == TypeKind.ARRAY) {
        designedType = ((ArrayType) iterableType).getComponentType();
    }
    if (designedType == null) {
        return null;
    }
    return JavaPluginUtils.resolveCapturedType(info, designedType);
}
 
Example 13
Project: incubator-netbeans   File: BeanModelBuilder.java   Source Code and License Vote up 5 votes
private TypeMirror  getHandlerBaseType() {
    if (eventHandlerBase == null) {
        TypeElement el = compilationInfo.getElements().getTypeElement(JAVAFX_EVENT_BASE);
        if (el == null) {
            // FIXME - better exception, must be catched & reported outside
            throw new IllegalStateException();
        }
        eventHandlerBase = el.asType();
    }
    return eventHandlerBase;
}
 
Example 14
Project: incubator-netbeans   File: NoLoggers.java   Source Code and License Vote up 4 votes
@TriggerTreeKind({Tree.Kind.ANNOTATION_TYPE, Tree.Kind.CLASS, Tree.Kind.ENUM, Tree.Kind.INTERFACE})
public static Iterable<ErrorDescription> checkNoLoggers(HintContext ctx) {
    Element cls = ctx.getInfo().getTrees().getElement(ctx.getPath());
    if (cls == null || cls.getKind() != ElementKind.CLASS || cls.getModifiers().contains(Modifier.ABSTRACT) ||
        (cls.getEnclosingElement() != null && cls.getEnclosingElement().getKind() != ElementKind.PACKAGE)
    ) {
        return null;
    }

    TypeElement loggerTypeElement = ctx.getInfo().getElements().getTypeElement("java.util.logging.Logger"); // NOI18N
    if (loggerTypeElement == null) {
        return null;
    }
    TypeMirror loggerTypeElementAsType = loggerTypeElement.asType();
    if (loggerTypeElementAsType == null || loggerTypeElementAsType.getKind() != TypeKind.DECLARED) {
        return null;
    }

    List<TypeMirror> customLoggersList = new ArrayList<>();
    if (isCustomEnabled(ctx.getPreferences())) {
        List<String> customLoggerClasses = getCustomLoggers(ctx.getPreferences());
        if (customLoggerClasses != null) {
            for (String className : customLoggerClasses) {
                TypeElement customTypeElement = ctx.getInfo().getElements().getTypeElement(className);
                if (customTypeElement == null) {
                    continue;
                }
                TypeMirror customTypeMirror = customTypeElement.asType();
                if (customTypeMirror == null || customTypeMirror.getKind() != TypeKind.DECLARED) {
                    continue;
                }
                customLoggersList.add(customTypeMirror);
            }
        }
    }

    List<VariableElement> loggerFields = new LinkedList<VariableElement>();
    List<VariableElement> fields = ElementFilter.fieldsIn(cls.getEnclosedElements());
    for(VariableElement f : fields) {
        if (f.getKind() != ElementKind.FIELD) {
            continue;
        }

        if (f.asType().equals(loggerTypeElementAsType)) {
            loggerFields.add(f);
        } else if (customLoggersList.contains(f.asType())) {
            loggerFields.add(f);
        }
    }

    if (loggerFields.size() == 0) {
        return Collections.singleton(ErrorDescriptionFactory.forName(
                ctx,
                ctx.getPath(),
                NbBundle.getMessage(NoLoggers.class, "MSG_NoLoggers_checkNoLoggers", cls), //NOI18N
                new NoLoggersFix(NbBundle.getMessage(NoLoggers.class, "MSG_NoLoggers_checkNoLoggers_Fix", cls), TreePathHandle.create(cls, ctx.getInfo())).toEditorFix() //NOI18N
        ));
    } else {
        return null;
    }
}
 
Example 15
Project: incubator-netbeans   File: Analyzer.java   Source Code and License Vote up 4 votes
@Override
    public Void visitThrows(ThrowsTree tree, List<ErrorDescription> errors) {
        boolean oldInheritDoc = foundInheritDoc;
        ReferenceTree exName = tree.getExceptionName();
        DocTreePath refPath = new DocTreePath(getCurrentPath(), tree.getExceptionName());
        Element ex = javac.getDocTrees().getElement(refPath);
        Types types = javac.getTypes();
        Elements elements = javac.getElements();
        final TypeElement throwableEl = elements.getTypeElement("java.lang.Throwable");
        final TypeElement errorEl = elements.getTypeElement("java.lang.Error");
        final TypeElement runtimeEl = elements.getTypeElement("java.lang.RuntimeException");
        if(throwableEl == null || errorEl == null || runtimeEl == null) {
            LOG.warning("Broken java-platform, cannot resolve " + throwableEl == null? "java.lang.Throwable" : errorEl == null? "java.lang.Error" : "java.lang.RuntimeException"); //NOI18N
            return null;
        }
        TypeMirror throwable = throwableEl.asType();
        TypeMirror error = errorEl.asType();
        TypeMirror runtime = runtimeEl.asType();
        DocTreePath currentDocPath = getCurrentPath();
        DocTreePathHandle dtph = DocTreePathHandle.create(currentDocPath, javac);
        if(dtph == null) {
            return null;
        }
        DocSourcePositions sp = (DocSourcePositions) javac.getTrees().getSourcePositions();
        int start = (int) sp.getStartPosition(javac.getCompilationUnit(), currentDocPath.getDocComment(), tree);
        int end = (int) sp.getEndPosition(javac.getCompilationUnit(), currentDocPath.getDocComment(), tree);
        if (ex == null || (ex.asType().getKind() == TypeKind.DECLARED
                && types.isAssignable(ex.asType(), throwable))) {
            switch (currentElement.getKind()) {
                case CONSTRUCTOR:
                case METHOD:
                    if (ex == null || !(types.isAssignable(ex.asType(), error)
                            || types.isAssignable(ex.asType(), runtime))) {
                        ExecutableElement ee = (ExecutableElement) currentElement;
                        String fqn;
                        if (ex != null) {
                            fqn = ((TypeElement) ex).getQualifiedName().toString();
                        } else {
                            ExpressionTree referenceClass = javac.getTreeUtilities().getReferenceClass(new DocTreePath(currentDocPath, exName));
                            if(referenceClass == null) break;
                            fqn = referenceClass.toString();
                        }
                        checkThrowsDeclared(tree, ex, fqn, ee.getThrownTypes(), dtph, start, end, errors);
                    }
                    break;
                default:
//                        env.messages.error(REFERENCE, tree, "dc.invalid.throws");
            }
        } else {
//                env.messages.error(REFERENCE, tree, "dc.invalid.throws");
        }
        warnIfEmpty(tree, tree.getDescription());
        super.visitThrows(tree, errors);
        foundInheritDoc = oldInheritDoc;
        return null;
    }
 
Example 16
Project: incubator-netbeans   File: GeneratorUtilitiesTest.java   Source Code and License Vote up 4 votes
protected TypeMirror returnType(CompilationInfo info) {
    TypeElement returnTypeElement = info.getElements().getTypeElement(returnTypeName);

    return returnTypeElement.asType();
}
 
Example 17
Project: incubator-netbeans   File: PropertyHyperlinkProcessor.java   Source Code and License Vote up 4 votes
@Override
public void run(CompilationController cc) throws Exception {
    cc.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
    int dotIndex = propChain.lastIndexOf("."); //NOI18N
    if (className == null) {
        return;
    }
    TypeElement te = JavaUtils.findClassElementByBinaryName(className, cc);
    if (te == null) {
        return;
    }
    TypeMirror startType = te.asType();
    ElementUtilities eu = cc.getElementUtilities();

    // property chain
    if (dotIndex != -1) {
        String getterChain = propChain.substring(0, dotIndex);
        StringTokenizer tokenizer = new StringTokenizer(getterChain, "."); //NOI18N
        while (tokenizer.hasMoreTokens() && startType != null) {
            String propertyName = tokenizer.nextToken();
            Property[] props = new PropertyFinder(startType, propertyName, eu, MatchType.PREFIX).findProperties();

            // no matching element found
            if (props.length == 0 || props[0].getGetter() == null) {
                startType = null;
                break;
            }

            TypeMirror retType = props[0].getGetter().getReturnType();
            if (retType.getKind() == TypeKind.DECLARED) {
                startType = retType;
            } else {
                startType = null;
            }
        }
    }

    if (startType == null) {
        return;
    }

    elementFound.set(true);
    String setterProp = propChain.substring(dotIndex + 1);
    Property[] sProps = new PropertyFinder(startType, setterProp, eu, MatchType.PREFIX).findProperties();
    if (sProps.length > 0) {
        ExecutableElement element = jumpToGetter ? sProps[0].getGetter() : sProps[0].getSetter();
        if (element != null) {
            ElementOpen.open(cc.getClasspathInfo(), element);
        }
    }
}
 
Example 18
Project: incubator-netbeans   File: GeneratorUtilsTest.java   Source Code and License Vote up 4 votes
protected TypeMirror returnType(CompilationInfo info) {
    TypeElement returnTypeElement = info.getElements().getTypeElement(returnTypeName);
    
    return returnTypeElement.asType();
}
 
Example 19
Project: annotation-processor-toolkit   File: TypeUtils.java   Source Code and License Vote up 3 votes
/**
 * Gets a TypeMirror for a full qualified class name.
 *
 * @param fullQualifiedClassName
 * @return the type mirror for the passed full qualified class name or null if corresponding type element can't be found
 */
public TypeMirror getTypeMirror(String fullQualifiedClassName) {

    TypeElement typeElement = getTypeElement(fullQualifiedClassName);
    return typeElement != null ? typeElement.asType() : null;

}
 
Example 20
Project: incubator-netbeans   File: AddPropertyCodeGenerator.java   Source Code and License Vote up 3 votes
private static TypeMirror resolve(CompilationInfo info, String s) {
    TypeElement te = info.getElements().getTypeElement(s);
    
    if (te == null) return null;
    
    return te.asType();
}